Added tray function for windows and linux(kde/gnome). Global shortcut to show/hide program windows
Moorly CI / windows-build (push) Successful in 3m54s
Moorly CI / linux-build (push) Successful in 4m12s

This commit is contained in:
Squid committed 2026-11-08 20:37:19 +01:00
1 parent 0fe753f16e
commit abbca0e411
5 files changed
+522 -18

No files matched your search

Generated
+125 -1
View File
@@ -117,6 +117,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "arc-swap"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92"
dependencies = [
"rustversion",
]
[[package]] [[package]]
name = "argon2" name = "argon2"
version = "0.6.0" version = "0.6.0"
@@ -841,6 +850,15 @@ dependencies = [
"crossbeam-utils", "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]] [[package]]
name = "crossbeam-utils" name = "crossbeam-utils"
version = "0.8.23" version = "0.8.23"
@@ -1256,6 +1274,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" 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]] [[package]]
name = "ff" name = "ff"
version = "0.14.0" version = "0.14.0"
@@ -1285,7 +1312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [ dependencies = [
"crc32fast", "crc32fast",
"miniz_oxide", "miniz_oxide 0.9.1",
"zlib-rs", "zlib-rs",
] ]
@@ -2194,6 +2221,26 @@ version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" 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]] [[package]]
name = "kurbo" name = "kurbo"
version = "0.10.4" version = "0.10.4"
@@ -2398,6 +2445,16 @@ dependencies = [
"paste", "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]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.9.1" version = "0.9.1"
@@ -2459,12 +2516,31 @@ dependencies = [
"serde", "serde",
"tokio", "tokio",
"toml", "toml",
"tray-icon",
"ttf-parser", "ttf-parser",
"uuid", "uuid",
"vt100", "vt100",
"windows-sys 0.61.2", "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]] [[package]]
name = "mundy" name = "mundy"
version = "0.2.3" version = "0.2.3"
@@ -3119,6 +3195,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]] [[package]]
name = "pbkdf2" name = "pbkdf2"
version = "0.13.0" version = "0.13.0"
@@ -3248,6 +3330,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" 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]] [[package]]
name = "polling" name = "polling"
version = "3.11.0" version = "3.11.0"
@@ -4228,6 +4323,15 @@ dependencies = [
"libc", "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]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.27.0" version = "3.27.0"
@@ -4479,6 +4583,26 @@ dependencies = [
"once_cell", "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]] [[package]]
name = "ttf-parser" name = "ttf-parser"
version = "0.25.1" version = "0.25.1"
+2
View File
@@ -23,8 +23,10 @@ global-hotkey = "0.9.0"
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.14.0", features = ["global_shortcuts"] } ashpd = { version = "0.14.0", features = ["global_shortcuts"] }
tray-icon = { version = "0.26.1", default-features = false, features = ["ksni"] }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
tray-icon = { version = "0.26.1", default-features = false }
windows-sys = { version = "0.61.2", features = [ windows-sys = { version = "0.61.2", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_Security", "Win32_Security",
+1 -1
View File
@@ -383,7 +383,7 @@ fn detect_backend() -> Backend {
} }
#[cfg(target_os = "linux")] #[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_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE") || std::env::var("XDG_SESSION_TYPE")
.is_ok_and(|session| session.eq_ignore_ascii_case("wayland")) .is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))
+206 -16
View File
@@ -23,6 +23,8 @@ mod notifications;
#[allow(dead_code)] #[allow(dead_code)]
mod terminal; mod terminal;
mod theme; mod theme;
#[cfg_attr(test, allow(dead_code))]
mod tray;
const MENUBAR_HEIGHT: f32 = 40.0; const MENUBAR_HEIGHT: f32 = 40.0;
/// Settings heading sizes: tab title, sub-section header, normal text, caption. /// Settings heading sizes: tab title, sub-section header, normal text, caption.
@@ -123,6 +125,21 @@ fn boot() -> (Moorly, Task<Message>) {
#[cfg(not(test))] #[cfg(not(test))]
hotkeys::start(global_hotkey_bindings(&state)); 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])) (state, Task::batch([task.map(|_| Message::Ignore), fonts]))
} }
@@ -368,6 +385,7 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
terminal_keys, terminal_keys,
terminal_text, terminal_text,
hotkeys::subscription().map(Message::Hotkey), hotkeys::subscription().map(Message::Hotkey),
tray::subscription().map(Message::Tray),
iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes),
window::events().map(|(window, event)| Message::WindowEvent(window, event)), window::events().map(|(window, event)| Message::WindowEvent(window, event)),
iced::event::listen_with(pointer_event), iced::event::listen_with(pointer_event),
@@ -1676,6 +1694,12 @@ struct Moorly {
main_window: Option<window::Id>, main_window: Option<window::Id>,
focused_window: Option<window::Id>, focused_window: Option<window::Id>,
main_window_hidden: bool, 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<WindowState>,
tray_available: bool,
close_to_tray: bool,
close_to_tray_draft: bool,
drag: Option<TabDrag>, drag: Option<TabDrag>,
theme: theme::Preference, theme: theme::Preference,
saved_theme: theme::Preference, saved_theme: theme::Preference,
@@ -2489,12 +2513,17 @@ impl Default for ConfigFile {
struct GeneralConfig { struct GeneralConfig {
#[serde(default = "default_true")] #[serde(default = "default_true")]
fade_settings: bool, 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 { impl Default for GeneralConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
fade_settings: true, fade_settings: true,
close_to_tray: false,
} }
} }
} }
@@ -4445,6 +4474,7 @@ fn new_tab_close_animation() -> Animation<bool> {
fn apply_settings(state: &mut Moorly) { fn apply_settings(state: &mut Moorly) {
state.show_start_tab = state.show_start_tab_draft; state.show_start_tab = state.show_start_tab_draft;
state.fade_settings = state.fade_settings_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.hide_tab_close = state.hide_tab_close_draft;
state.show_new_session_button = state.show_new_session_button_draft; state.show_new_session_button = state.show_new_session_button_draft;
state.show_command_palette_description = state.show_command_palette_description_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) { fn undo_settings(state: &mut Moorly) {
state.show_start_tab_draft = state.show_start_tab; state.show_start_tab_draft = state.show_start_tab;
state.fade_settings_draft = state.fade_settings; 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.hide_tab_close_draft = state.hide_tab_close;
state.show_new_session_button_draft = state.show_new_session_button; state.show_new_session_button_draft = state.show_new_session_button;
state.show_command_palette_description_draft = state.show_command_palette_description; state.show_command_palette_description_draft = state.show_command_palette_description;
@@ -4533,6 +4564,7 @@ fn config_file(state: &Moorly) -> ConfigFile {
ConfigFile { ConfigFile {
general: GeneralConfig { general: GeneralConfig {
fade_settings: state.fade_settings, fade_settings: state.fade_settings,
close_to_tray: state.close_to_tray,
}, },
startup: StartupConfig { startup: StartupConfig {
show_start_tab: state.show_start_tab, show_start_tab: state.show_start_tab,
@@ -4607,6 +4639,7 @@ impl Default for Moorly {
builtin_toast_config(&config.appearance); builtin_toast_config(&config.appearance);
let show_start_tab = config.startup.show_start_tab; let show_start_tab = config.startup.show_start_tab;
let fade_settings = config.general.fade_settings; 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 hide_tab_close = config.appearance.hide_tab_close;
let show_new_session_button = config.appearance.show_new_session_button; let show_new_session_button = config.appearance.show_new_session_button;
let show_command_palette_description = config.appearance.show_command_palette_description; let show_command_palette_description = config.appearance.show_command_palette_description;
@@ -4634,6 +4667,10 @@ impl Default for Moorly {
main_window: None, main_window: None,
focused_window: None, focused_window: None,
main_window_hidden: false, main_window_hidden: false,
hidden_main_window: None,
tray_available: false,
close_to_tray,
close_to_tray_draft: close_to_tray,
drag: None, drag: None,
theme, theme,
saved_theme: theme, saved_theme: theme,
@@ -4762,6 +4799,7 @@ enum Message {
SelectSettingsSection(SettingsSection), SelectSettingsSection(SettingsSection),
SetShowStartTab(bool), SetShowStartTab(bool),
SetFadeSettings(bool), SetFadeSettings(bool),
SetCloseToTray(bool),
SetHideTabClose(bool), SetHideTabClose(bool),
SetShowNewSessionButton(bool), SetShowNewSessionButton(bool),
SetShowCommandPaletteDescription(bool), SetShowCommandPaletteDescription(bool),
@@ -4900,6 +4938,7 @@ enum Message {
ScrollTabs(window::Id, mouse::ScrollDelta), ScrollTabs(window::Id, mouse::ScrollDelta),
ScrollTabsBy(window::Id, f32), ScrollTabsBy(window::Id, f32),
Hotkey(hotkeys::Event), Hotkey(hotkeys::Event),
Tray(tray::Event),
FinishToggleWindowVisibility(Option<bool>), FinishToggleWindowVisibility(Option<bool>),
Quit, Quit,
} }
@@ -5509,6 +5548,7 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
} }
Message::SetShowStartTab(value) => state.show_start_tab_draft = value, Message::SetShowStartTab(value) => state.show_start_tab_draft = value,
Message::SetFadeSettings(value) => state.fade_settings_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::SetHideTabClose(value) => state.hide_tab_close_draft = value,
Message::SetShowNewSessionButton(value) => state.show_new_session_button_draft = value, Message::SetShowNewSessionButton(value) => state.show_new_session_button_draft = value,
Message::SetShowCommandPaletteDescription(value) => { Message::SetShowCommandPaletteDescription(value) => {
@@ -6213,10 +6253,12 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
return scroll_tabs_by(state, window, amount); return scroll_tabs_by(state, window, amount);
} }
Message::Hotkey(event) => return handle_hotkey_event(state, event), Message::Hotkey(event) => return handle_hotkey_event(state, event),
Message::Tray(event) => return handle_tray_event(state, event),
Message::FinishToggleWindowVisibility(minimized) => { Message::FinishToggleWindowVisibility(minimized) => {
return finish_toggle_window_visibility(state, minimized); return finish_toggle_window_visibility(state, minimized);
} }
Message::Quit => { Message::Quit => {
tray::shutdown();
hotkeys::shutdown(); hotkeys::shutdown();
// Drop PTY sessions explicitly so their child processes are // Drop PTY sessions explicitly so their child processes are
// terminated before process::exit bypasses the state destructor. // terminated before process::exit bypasses the state destructor.
@@ -6245,12 +6287,17 @@ fn main_window_id(state: &Moorly) -> Option<window::Id> {
} }
fn show_main_window(state: &mut Moorly) -> Task<Message> { fn show_main_window(state: &mut Moorly) -> Task<Message> {
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 { let Some(window) = main_window_id(state) else {
return Task::none(); return Task::none();
}; };
state.main_window_hidden = false; state.main_window_hidden = false;
state.focused_window = Some(window); state.focused_window = Some(window);
tray::set_window_visible(true);
Task::batch([ Task::batch([
window::set_mode(window, window::Mode::Windowed), window::set_mode(window, window::Mode::Windowed),
@@ -6259,39 +6306,126 @@ fn show_main_window(state: &mut Moorly) -> Task<Message> {
]) ])
} }
fn toggle_main_window(state: &mut Moorly) -> Task<Message> { /// Wayland cannot unmap or restore an existing toplevel, so the hidden window
let Some(window) = main_window_id(state) else { /// is recreated from its saved UI state.
return Task::none(); fn reopen_main_window(state: &mut Moorly, window_state: WindowState) -> Task<Message> {
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<Message> {
if state.main_window_hidden { if state.main_window_hidden {
return show_main_window(state); 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 // A minimized window is still visible as far as `Mode` is concerned, so
// ask the platform before deciding to hide it. // ask the platform before deciding to hide it.
window::is_minimized(window).map(Message::FinishToggleWindowVisibility) window::is_minimized(window).map(Message::FinishToggleWindowVisibility)
} }
fn finish_toggle_window_visibility(state: &mut Moorly, minimized: Option<bool>) -> Task<Message> { fn finish_toggle_window_visibility(state: &mut Moorly, minimized: Option<bool>) -> Task<Message> {
let Some(window) = main_window_id(state) else {
return Task::none();
};
if minimized == Some(true) { 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); return show_main_window(state);
} }
state.main_window_hidden = true; hide_main_window(state)
window::set_mode(window, window::Mode::Hidden)
} }
fn open_palette_from_hotkey(state: &mut Moorly) -> Task<Message> { 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<Message> {
if state.main_window_hidden || state.hidden_main_window.is_some() {
return Task::none();
}
let Some(window) = main_window_id(state) else { let Some(window) = main_window_id(state) else {
return Task::none(); 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<Message> {
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<Message> {
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<Message> {
let show = show_main_window(state); let show = show_main_window(state);
let Some(window) = main_window_id(state) else {
return show;
};
let palette = update(state, Message::ToggleCommandPalette(window)); let palette = update(state, Message::ToggleCommandPalette(window));
Task::batch([show, palette]) 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_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 => { 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); remove_window(state, window);
if state.windows.is_empty() { if state.windows.is_empty() {
tray::shutdown();
hotkeys::shutdown(); hotkeys::shutdown();
return iced::exit(); return iced::exit();
} }
@@ -6415,6 +6561,11 @@ fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) ->
remove_window(state, window); remove_window(state, window);
if state.windows.is_empty() { if state.windows.is_empty() {
if state.hidden_main_window.is_some() {
return Task::none();
}
tray::shutdown();
hotkeys::shutdown(); hotkeys::shutdown();
return iced::exit(); return iced::exit();
} }
@@ -6844,6 +6995,8 @@ fn close_window_if_empty(state: &mut Moorly, window: window::Id) -> Task<Message
remove_window(state, window); remove_window(state, window);
if state.windows.is_empty() { if state.windows.is_empty() {
tray::shutdown();
hotkeys::shutdown();
return iced::exit(); return iced::exit();
} }
@@ -9471,12 +9624,21 @@ fn command_palette_row(
} }
fn general_panel(state: &Moorly) -> Element<'_, Message> { fn general_panel(state: &Moorly) -> Element<'_, Message> {
row![ column![
styled_text(&state.typography.h3, "Fade In/Fade out animation"), row![
space::horizontal(), styled_text(&state.typography.h3, "Fade In/Fade out animation"),
toggler(state.fade_settings_draft).on_toggle(Message::SetFadeSettings), 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() .into()
} }
@@ -11098,6 +11260,10 @@ mod tests {
main_window: Some(window), main_window: Some(window),
focused_window: Some(window), focused_window: Some(window),
main_window_hidden: false, main_window_hidden: false,
hidden_main_window: None,
tray_available: false,
close_to_tray: false,
close_to_tray_draft: false,
drag: None, drag: None,
theme: theme::Preference::default(), theme: theme::Preference::default(),
saved_theme: theme::Preference::default(), saved_theme: theme::Preference::default(),
@@ -13918,4 +14084,28 @@ start_path = "/tmp"
std::fs::remove_dir_all(&root).unwrap(); 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));
}
} }
+188
View File
@@ -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<broadcast::Sender<Event>> = 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<Event> {
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<Option<TrayIcon>> = const { RefCell::new(None) };
static TOGGLE_ITEM: RefCell<Option<MenuItem>> = 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) {}
}