From cb512d743b577fddb83f010d7e26b6292f54cb9b Mon Sep 17 00:00:00 2001 From: squid Date: Thu, 12 Nov 2026 22:18:18 +0100 Subject: [PATCH] Added program icons --- Cargo.lock | 54 ++++++- Cargo.toml | 4 + assets/dev.moorly.Moorly.desktop | 2 +- build.rs | 15 ++ src/autostart.rs | 15 +- src/hotkeys.rs | 13 +- src/icons.rs | 248 +++++++++++++++++++++++++++++++ src/main.rs | 215 +++++++++++++++++++++------ src/tray.rs | 66 ++++---- 9 files changed, 540 insertions(+), 92 deletions(-) create mode 100644 build.rs create mode 100644 src/icons.rs diff --git a/Cargo.lock b/Cargo.lock index 59896e6..959ae50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2523,16 +2523,18 @@ dependencies = [ "iced_aw", "instance-handoff", "nix", + "png", "russh", "russh-sftp", "serde", "tokio", - "toml", + "toml 0.8.23", "tray-icon", "ttf-parser", "uuid", "vt100", "windows-sys 0.61.2", + "winresource", ] [[package]] @@ -3929,6 +3931,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "serdect" version = "0.4.3" @@ -4499,11 +4510,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", - "serde_spanned", + "serde_spanned 0.6.9", "toml_datetime 0.6.11", "toml_edit 0.22.27", ] +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.4", +] + [[package]] name = "toml_datetime" version = "0.6.11" @@ -4515,9 +4541,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -4530,7 +4556,7 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap", "serde", - "serde_spanned", + "serde_spanned 0.6.9", "toml_datetime 0.6.11", "toml_write", "winnow 0.7.15", @@ -4543,7 +4569,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", - "toml_datetime 1.1.2+spec-1.1.0", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", "winnow 1.0.4", ] @@ -4563,6 +4589,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tracing" version = "0.1.44" @@ -5491,6 +5523,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" +dependencies = [ + "toml 1.2.1+spec-1.1.0", + "version_check", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index cc2ea9c..9f845c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ edition = "2024" iced = { version = "0.14.0", features = ["tokio", "advanced"] } iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["color_picker"] } instance-handoff = "=0.1.0-alpha.2" +png = "0.18" russh = "0.65.0" russh-sftp = "3.0.1" serde = { version = "1.0.229", features = ["derive"] } @@ -35,3 +36,6 @@ windows-sys = { version = "0.61.2", features = [ "Win32_System_Pipes", "Win32_System_Threading", ] } + +[build-dependencies] +winresource = "0.1" diff --git a/assets/dev.moorly.Moorly.desktop b/assets/dev.moorly.Moorly.desktop index 84ec2f6..8d2196f 100644 --- a/assets/dev.moorly.Moorly.desktop +++ b/assets/dev.moorly.Moorly.desktop @@ -3,7 +3,7 @@ Type=Application Name=Moorly Comment=SSH and terminal client Exec=moorly -Icon=utilities-terminal +Icon=dev.moorly.Moorly Terminal=false Categories=Network;Utility;TerminalEmulator; StartupNotify=true diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..b276917 --- /dev/null +++ b/build.rs @@ -0,0 +1,15 @@ +fn main() { + println!("cargo:rerun-if-changed=assets/icons/ico/moorly.ico"); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { + return; + } + + let mut resource = winresource::WindowsResource::new(); + resource.set_icon("assets/icons/ico/moorly.ico"); + resource.set("ProductName", "Moorly"); + resource.set("FileDescription", "Moorly"); + resource + .compile() + .expect("failed to embed the Windows icon resource"); +} diff --git a/src/autostart.rs b/src/autostart.rs index 1c15e6d..0a2d4be 100644 --- a/src/autostart.rs +++ b/src/autostart.rs @@ -59,7 +59,12 @@ pub fn enable() -> Result<(), String> { } std::fs::write(&path, entry_contents(&executable)) - .map_err(|error| format!("Could not write the autostart entry: {error}")) + .map_err(|error| format!("Could not write the autostart entry: {error}"))?; + + #[cfg(target_os = "linux")] + crate::icons::refresh_linux_caches(); + + Ok(()) } /// Removes our autostart entry, leaving every other entry untouched. @@ -86,7 +91,7 @@ fn entry_contents(executable: &std::path::Path) -> String { Name=Moorly\n\ Comment=SSH and terminal client\n\ Exec=\"{executable}\"\n\ - Icon=utilities-terminal\n\ + Icon=dev.moorly.Moorly\n\ Terminal=false\n\ Categories=Network;Utility;TerminalEmulator;\n\ StartupNotify=true\n\ @@ -97,10 +102,7 @@ fn entry_contents(executable: &std::path::Path) -> String { #[cfg(windows)] fn entry_contents(executable: &std::path::Path) -> String { - format!( - "@echo off\r\nstart \"\" \"{}\"\r\n", - executable.display() - ) + format!("@echo off\r\nstart \"\" \"{}\"\r\n", executable.display()) } #[cfg(not(any(target_os = "linux", windows)))] @@ -115,6 +117,7 @@ mod tests { let entry = super::entry_contents(std::path::Path::new("/usr/bin/moorly")); assert!(entry.contains("Exec=\"/usr/bin/moorly\"")); + assert!(entry.contains("Icon=dev.moorly.Moorly")); assert!(entry.contains("X-Moorly-Generated=true")); } } diff --git a/src/hotkeys.rs b/src/hotkeys.rs index a41502a..f6569db 100644 --- a/src/hotkeys.rs +++ b/src/hotkeys.rs @@ -417,8 +417,9 @@ fn ensure_desktop_entry() { let applications = data_dir.join("applications"); let path = applications.join(format!("{APP_ID}.desktop")); + let existing = std::fs::read_to_string(&path).ok(); - if let Ok(existing) = std::fs::read_to_string(&path) + if let Some(existing) = &existing && !existing.contains("X-Moorly-Generated=true") { // A packaged entry (or the user's own entry) is authoritative. @@ -436,7 +437,7 @@ fn ensure_desktop_entry() { Name=Moorly\n\ Comment=SSH and terminal client\n\ Exec=\"{executable}\"\n\ - Icon=utilities-terminal\n\ + Icon=dev.moorly.Moorly\n\ Terminal=false\n\ Categories=Network;Utility;TerminalEmulator;\n\ StartupNotify=true\n\ @@ -444,8 +445,12 @@ fn ensure_desktop_entry() { X-Moorly-Generated=true\n" ); - if std::fs::create_dir_all(&applications).is_ok() { - let _ = std::fs::write(path, entry); + if existing.as_deref() == Some(entry.as_str()) { + return; + } + + if std::fs::create_dir_all(&applications).is_ok() && std::fs::write(path, entry).is_ok() { + crate::icons::refresh_linux_caches(); } } diff --git a/src/icons.rs b/src/icons.rs new file mode 100644 index 0000000..6ae32e3 --- /dev/null +++ b/src/icons.rs @@ -0,0 +1,248 @@ +//! Embedded application icon resources. +//! +//! The same PNGs feed the window icon, the system tray and the Linux hicolor +//! icon theme, so the binary never depends on an external image file. + +use serde::{Deserialize, Serialize}; + +/// Color application logo, also used by the Linux desktop entry and tray. +pub const APP_ICON_PNG: &[u8] = include_bytes!("../assets/icons/color/moorly_logo_256x256.png"); +/// Monochrome tray icon. +pub const TRAY_MONOCHROME_PNG: &[u8] = + include_bytes!("../assets/icons/monochrome/moorly_logo_monochrome_256x256.png"); + +/// Selected icon variant for the system tray. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TrayIconStyle { + #[default] + Color, + Monochrome, +} + +impl TrayIconStyle { + pub const ALL: [Self; 2] = [Self::Color, Self::Monochrome]; + + pub fn label(self) -> &'static str { + match self { + Self::Color => "Color", + Self::Monochrome => "Monochrome", + } + } + + fn png(self) -> &'static [u8] { + match self { + Self::Color => APP_ICON_PNG, + Self::Monochrome => TRAY_MONOCHROME_PNG, + } + } +} + +/// Decoded RGBA icon for the system tray. +#[cfg(any(target_os = "linux", target_os = "windows"))] +pub fn tray_icon(style: TrayIconStyle) -> Result { + let (rgba, width, height) = decode_rgba(style.png())?; + + tray_icon::Icon::from_rgba(rgba, width, height) + .map_err(|error| format!("Could not create the system tray icon: {error}")) +} + +/// Window and taskbar icon, decoded once per window from the embedded logo. +pub fn window_icon() -> Option { + let (rgba, width, height) = decode_rgba(APP_ICON_PNG).ok()?; + + iced::window::icon::from_rgba(rgba, width, height).ok() +} + +/// Makes the logo available under the XDG hicolor icon theme so the desktop +/// entry can resolve `Icon=dev.moorly.Moorly` from any working directory. +#[cfg(target_os = "linux")] +pub fn install_linux_icon() { + let Some(data_dir) = linux_data_dir() else { + return; + }; + + install_linux_icon_in(&data_dir); + // The icon may already exist from an older build, so always invalidate the + // icon and desktop caches instead of only doing it when the file changes. + refresh_linux_caches_in(&data_dir); +} + +/// Refreshes the icon and desktop caches after a generated desktop entry +/// changed, without requiring a Plasma restart. +#[cfg(target_os = "linux")] +pub fn refresh_linux_caches() { + if let Some(data_dir) = linux_data_dir() { + refresh_linux_caches_in(&data_dir); + } +} + +#[cfg(target_os = "linux")] +fn linux_data_dir() -> Option { + std::env::var_os("XDG_DATA_HOME") + .map(std::path::PathBuf::from) + .or_else(|| { + std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".local/share")) + }) +} + +#[cfg(target_os = "linux")] +fn install_linux_icon_in(data_dir: &std::path::Path) { + let path = data_dir + .join("icons") + .join("hicolor") + .join("256x256") + .join("apps") + .join(format!("{}.png", crate::hotkeys::APP_ID)); + + // Repair an icon left behind by an older build instead of keeping a stale + // monochrome or otherwise wrong image. + if std::fs::read(&path).is_ok_and(|current| current == APP_ICON_PNG) { + return; + } + + if let Some(parent) = path.parent() + && std::fs::create_dir_all(parent).is_ok() + { + let _ = std::fs::write(path, APP_ICON_PNG); + } +} + +#[cfg(target_os = "linux")] +fn refresh_linux_caches_in(data_dir: &std::path::Path) { + let hicolor = data_dir.join("icons").join("hicolor"); + + if hicolor.is_dir() { + // xdg-icon-resource uses the same trick to make icon loaders notice + // directory changes. + let dummy = hicolor.join(".xdg-icon-resource-dummy"); + let _ = std::fs::write(&dummy, []); + let _ = std::fs::remove_file(dummy); + + if hicolor.join("icon-theme.cache").is_file() { + let _ = spawn_cache_command( + "gtk-update-icon-cache", + &[ + std::ffi::OsStr::new("-f"), + std::ffi::OsStr::new("-t"), + std::ffi::OsStr::new("-q"), + hicolor.as_os_str(), + ], + ); + } + } + + if std::env::var_os("KDE_FULL_SESSION").is_some() + || std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|desktop| desktop.contains("KDE")) + { + let rebuild = + spawn_cache_command("kbuildsycoca6", &[std::ffi::OsStr::new("--noincremental")]); + + if rebuild.is_err() { + let _ = + spawn_cache_command("kbuildsycoca5", &[std::ffi::OsStr::new("--noincremental")]); + } + } +} + +#[cfg(target_os = "linux")] +fn spawn_cache_command( + program: &str, + args: &[&std::ffi::OsStr], +) -> std::io::Result { + std::process::Command::new(program) + .args(args) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() +} + +fn decode_rgba(bytes: &[u8]) -> Result<(Vec, u32, u32), String> { + let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); + + let mut reader = decoder + .read_info() + .map_err(|error| format!("Could not read the icon: {error}"))?; + let mut buffer = vec![ + 0; + reader + .output_buffer_size() + .ok_or_else(|| "The icon dimensions are invalid.".to_owned())? + ]; + let info = reader + .next_frame(&mut buffer) + .map_err(|error| format!("Could not decode the icon: {error}"))?; + buffer.truncate(info.buffer_size()); + + let rgba = match info.color_type { + png::ColorType::Rgba => buffer, + png::ColorType::Rgb => buffer + .chunks_exact(3) + .flat_map(|pixel| [pixel[0], pixel[1], pixel[2], u8::MAX]) + .collect(), + png::ColorType::Grayscale => buffer + .into_iter() + .flat_map(|value| [value, value, value, u8::MAX]) + .collect(), + png::ColorType::GrayscaleAlpha => buffer + .chunks_exact(2) + .flat_map(|pixel| [pixel[0], pixel[0], pixel[0], pixel[1]]) + .collect(), + png::ColorType::Indexed => { + return Err("The icon could not be expanded to RGBA.".to_owned()); + } + }; + + Ok((rgba, info.width, info.height)) +} + +#[cfg(test)] +mod tests { + use super::{TrayIconStyle, decode_rgba}; + + #[test] + fn embedded_tray_icons_decode_to_rgba() { + for style in TrayIconStyle::ALL { + let (rgba, width, height) = decode_rgba(style.png()).unwrap(); + + assert_eq!((width, height), (256, 256)); + assert_eq!(rgba.len(), 256 * 256 * 4); + } + + assert_eq!(TrayIconStyle::Color.png(), super::APP_ICON_PNG); + assert_eq!(TrayIconStyle::Monochrome.png(), super::TRAY_MONOCHROME_PNG); + } + + #[test] + fn window_icon_is_always_the_color_logo() { + let (rgba, size) = super::window_icon().unwrap().into_raw(); + let (expected, width, height) = decode_rgba(super::APP_ICON_PNG).unwrap(); + + assert_eq!(rgba, expected); + assert_eq!(size, iced::Size::new(width, height)); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_icon_is_installed_under_hicolor() { + let data = std::env::temp_dir().join(format!("moorly-icon-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&data); + + super::install_linux_icon_in(&data); + + let icon = data + .join("icons/hicolor/256x256/apps") + .join(format!("{}.png", crate::hotkeys::APP_ID)); + assert!(icon.is_file()); + assert_eq!(std::fs::read(&icon).unwrap(), super::APP_ICON_PNG); + + // An older build may have left the wrong variant in place. + std::fs::write(&icon, super::TRAY_MONOCHROME_PNG).unwrap(); + super::install_linux_icon_in(&data); + assert_eq!(std::fs::read(icon).unwrap(), super::APP_ICON_PNG); + + let _ = std::fs::remove_dir_all(data); + } +} diff --git a/src/main.rs b/src/main.rs index 097b75a..9013f3f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,7 @@ use iced::{ #[cfg_attr(test, allow(dead_code))] mod autostart; mod hotkeys; +mod icons; mod notifications; mod single_instance; #[allow(dead_code)] @@ -101,6 +102,9 @@ fn main() -> iced::Result { return Ok(()); } + #[cfg(target_os = "linux")] + icons::install_linux_icon(); + let result = iced::daemon(boot, update, view) .title(window_title) .theme(|state: &Moorly, _window| state.theme.iced()) @@ -123,6 +127,7 @@ fn window_settings(size: Size, position: Option) -> window::Settings { position: position.map_or(window::Position::Default, window::Position::Specific), min_size: Some(Size::new(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT)), exit_on_close_request: false, + icon: icons::window_icon(), ..window::Settings::default() } } @@ -155,7 +160,7 @@ fn boot() -> (Moorly, Task) { hotkeys::start(global_hotkey_bindings(&state)); #[cfg(not(test))] - match tray::start() { + match tray::start(state.tray_icon_style) { Ok(()) => { state.tray_available = true; tray::set_window_visible(true); @@ -1648,9 +1653,8 @@ impl Command { } // Best matches first; ties keep the original command order. - commands.sort_by_key(|command| { - std::cmp::Reverse(fuzzy_score(&command.label(state), query)) - }); + commands + .sort_by_key(|command| std::cmp::Reverse(fuzzy_score(&command.label(state), query))); commands } @@ -1861,8 +1865,7 @@ fn copy_terminal_selection(state: &mut Moorly, id: u32) -> Task { /// Reads the clipboard and hands it back for a single paste into the terminal. fn paste_terminal_clipboard(id: u32) -> Task { - iced::clipboard::read() - .map(move |contents| Message::TerminalPasteContents(id, contents)) + iced::clipboard::read().map(move |contents| Message::TerminalPasteContents(id, contents)) } /// Clipboard bytes for a paste, ignoring a missing or empty clipboard. Line @@ -1936,6 +1939,8 @@ struct Moorly { close_to_tray_draft: bool, minimize_to_tray: bool, minimize_to_tray_draft: bool, + tray_icon_style: icons::TrayIconStyle, + tray_icon_style_draft: icons::TrayIconStyle, right_click_behavior: RightClickBehavior, right_click_behavior_draft: RightClickBehavior, right_click_menu_open: bool, @@ -2768,6 +2773,9 @@ struct GeneralConfig { /// Minimizing the main window hides it to the tray instead. #[serde(default)] minimize_to_tray: bool, + /// Icon variant shown in the system tray. + #[serde(default)] + tray_icon_style: icons::TrayIconStyle, #[serde(default)] right_click_behavior: RightClickBehavior, } @@ -2778,6 +2786,7 @@ impl Default for GeneralConfig { fade_settings: true, close_to_tray: false, minimize_to_tray: false, + tray_icon_style: icons::TrayIconStyle::default(), right_click_behavior: RightClickBehavior::default(), } } @@ -4872,6 +4881,29 @@ fn new_tab_close_animation() -> Animation { Animation::new(false).duration(Duration::from_millis(750)) } +/// Applies a tray icon variant to the running tray. On failure the previous +/// icon stays in place and the error is reported to the user. +fn set_tray_icon_style(state: &mut Moorly, style: icons::TrayIconStyle) -> bool { + #[cfg(test)] + { + let _ = (state, style); + true + } + + #[cfg(not(test))] + { + if let Err(error) = tray::set_icon(style) { + state.notifications.add( + notifications::Notification::new(notifications::NotificationKind::Error, error) + .title("System tray icon"), + ); + return false; + } + + true + } +} + /// Commits the draft settings to the running state. fn apply_settings(state: &mut Moorly) { state.show_start_tab = state.show_start_tab_draft; @@ -4879,6 +4911,7 @@ fn apply_settings(state: &mut Moorly) { state.fade_settings = state.fade_settings_draft; state.close_to_tray = state.close_to_tray_draft; state.minimize_to_tray = state.minimize_to_tray_draft; + state.tray_icon_style = state.tray_icon_style_draft; state.right_click_behavior = state.right_click_behavior_draft; state.hide_tab_close = state.hide_tab_close_draft; state.show_new_session_button = state.show_new_session_button_draft; @@ -4922,6 +4955,7 @@ fn undo_settings(state: &mut Moorly) { state.fade_settings_draft = state.fade_settings; state.close_to_tray_draft = state.close_to_tray; state.minimize_to_tray_draft = state.minimize_to_tray; + state.tray_icon_style_draft = state.tray_icon_style; state.right_click_behavior_draft = state.right_click_behavior; state.hide_tab_close_draft = state.hide_tab_close; state.show_new_session_button_draft = state.show_new_session_button; @@ -4975,6 +5009,7 @@ fn config_file(state: &Moorly) -> ConfigFile { fade_settings: state.fade_settings, close_to_tray: state.close_to_tray, minimize_to_tray: state.minimize_to_tray, + tray_icon_style: state.tray_icon_style, right_click_behavior: state.right_click_behavior, }, startup: StartupConfig { @@ -5078,6 +5113,7 @@ impl Default for Moorly { let fade_settings = config.general.fade_settings; let close_to_tray = config.general.close_to_tray; let minimize_to_tray = config.general.minimize_to_tray; + let tray_icon_style = config.general.tray_icon_style; 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; @@ -5116,6 +5152,8 @@ impl Default for Moorly { close_to_tray_draft: close_to_tray, minimize_to_tray, minimize_to_tray_draft: minimize_to_tray, + tray_icon_style, + tray_icon_style_draft: tray_icon_style, right_click_behavior: config.general.right_click_behavior, right_click_behavior_draft: config.general.right_click_behavior, right_click_menu_open: false, @@ -5273,6 +5311,7 @@ enum Message { SetFadeSettings(bool), SetCloseToTray(bool), SetMinimizeToTray(bool), + SetTrayIconStyle(icons::TrayIconStyle), SetRightClickBehavior(RightClickBehavior), ToggleRightClickBehaviorMenu, EnableAutostartAtLogin, @@ -6161,6 +6200,11 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::SetFadeSettings(value) => state.fade_settings_draft = value, Message::SetCloseToTray(value) => state.close_to_tray_draft = value, Message::SetMinimizeToTray(value) => state.minimize_to_tray_draft = value, + Message::SetTrayIconStyle(style) => { + if set_tray_icon_style(state, style) { + state.tray_icon_style_draft = style; + } + } Message::SetRightClickBehavior(behavior) => { state.right_click_behavior_draft = behavior; state.right_click_menu_open = false; @@ -6172,11 +6216,8 @@ fn update(state: &mut Moorly, message: Message) -> Task { Ok(()) => state.autostart_at_login = true, Err(error) => { state.notifications.add( - notifications::Notification::new( - notifications::NotificationKind::Error, - error, - ) - .title("Autostart at login"), + notifications::Notification::new(notifications::NotificationKind::Error, error) + .title("Autostart at login"), ); } }, @@ -6184,11 +6225,8 @@ fn update(state: &mut Moorly, message: Message) -> Task { Ok(()) => state.autostart_at_login = false, Err(error) => { state.notifications.add( - notifications::Notification::new( - notifications::NotificationKind::Error, - error, - ) - .title("Autostart at login"), + notifications::Notification::new(notifications::NotificationKind::Error, error) + .title("Autostart at login"), ); } }, @@ -6275,7 +6313,15 @@ fn update(state: &mut Moorly, message: Message) -> Task { save_config(state); sync_global_hotkeys(state); } - Message::UndoChanges => undo_settings(state), + Message::UndoChanges => { + let tray_icon_changed = state.tray_icon_style_draft != state.tray_icon_style; + undo_settings(state); + + if tray_icon_changed { + let style = state.tray_icon_style; + set_tray_icon_style(state, style); + } + } Message::Notification(action) => match action { notifications::Message::Dismiss(id) => state.notifications.dismiss(id), }, @@ -10423,6 +10469,39 @@ fn general_panel(state: &Moorly) -> Element<'_, Message> { ); } + let mut tray_style_picker = row![].spacing(6); + for style in icons::TrayIconStyle::ALL { + let item = button(text(style.label())) + .on_press(Message::SetTrayIconStyle(style)) + .padding([6, 10]); + + tray_style_picker = tray_style_picker.push(if style == state.tray_icon_style_draft { + item.style(theme::selected_option) + } else { + item.style(theme::outlined_option) + }); + } + + panel = panel.push( + column![ + styled_text(&state.typography.h2, "System Tray"), + row![ + column![ + styled_text(&state.typography.h3, "Tray icon style"), + styled_text( + &state.typography.caption, + "Choose the icon shown in the system tray.", + ), + ] + .spacing(4), + space::horizontal(), + tray_style_picker, + ] + .align_y(Alignment::Center), + ] + .spacing(8), + ); + panel = panel.push( column![ styled_text(&state.typography.h2, "Right-click behavior"), @@ -10586,9 +10665,11 @@ fn autostart_choices(state: &Moorly) -> Vec { for (profile_index, profile) in folder.profiles.iter().enumerate() { // Hide everything already in the draft list, including profiles // added since the last save. - if state.autostart_profiles_draft.iter().any(|entry| { - autostart_target(state, entry) == Some((folder_index, profile_index)) - }) { + if state + .autostart_profiles_draft + .iter() + .any(|entry| autostart_target(state, entry) == Some((folder_index, profile_index))) + { continue; } @@ -10827,7 +10908,12 @@ fn startup_panel(state: &Moorly) -> Element<'_, Message> { let choices = autostart_choices(state); let add = button("Add") - .on_press_maybe(state.autostart_choice.is_some().then_some(Message::AddAutostartProfile)) + .on_press_maybe( + state + .autostart_choice + .is_some() + .then_some(Message::AddAutostartProfile), + ) .padding([6, 16]) .style(theme::positive_option); @@ -11041,6 +11127,7 @@ fn settings_dirty(state: &Moorly) -> bool { || state.command_palette_enabled_draft != state.command_palette_enabled || state.close_to_tray_draft != state.close_to_tray || state.minimize_to_tray_draft != state.minimize_to_tray + || state.tray_icon_style_draft != state.tray_icon_style || state.right_click_behavior_draft != state.right_click_behavior || state.theme_choice != state.saved_theme_choice || state.shortcuts != state.saved_shortcuts @@ -12655,6 +12742,8 @@ mod tests { close_to_tray_draft: false, minimize_to_tray: false, minimize_to_tray_draft: false, + tray_icon_style: super::icons::TrayIconStyle::default(), + tray_icon_style_draft: super::icons::TrayIconStyle::default(), right_click_behavior: super::RightClickBehavior::default(), right_click_behavior_draft: super::RightClickBehavior::default(), right_click_menu_open: false, @@ -12834,10 +12923,7 @@ mod tests { // The quick rows plus both profiles. let quick_rows = 1 + usize::from(cfg!(windows)); assert_eq!(choices.len(), quick_rows + 2); - assert_eq!( - choices[0].profile.kind, - super::AutostartKind::QuickTerminal - ); + assert_eq!(choices[0].profile.kind, super::AutostartKind::QuickTerminal); let beta = choices .iter() @@ -12858,11 +12944,7 @@ mod tests { // Added profiles leave the drop-down until the draft is undone. let remaining = super::autostart_choices(&state); assert_eq!(remaining.len(), quick_rows + 1); - assert!( - !remaining - .iter() - .any(|choice| choice.profile.name == "Beta") - ); + assert!(!remaining.iter().any(|choice| choice.profile.name == "Beta")); let _ = update(&mut state, Message::AutostartChoiceSelected(alpha.clone())); let _ = update(&mut state, Message::AddAutostartProfile); @@ -12910,10 +12992,7 @@ mod tests { let quick = super::autostart_choices(&state)[0].clone(); for _ in 0..3 { - let _ = update( - &mut state, - Message::AutostartChoiceSelected(quick.clone()), - ); + let _ = update(&mut state, Message::AutostartChoiceSelected(quick.clone())); let _ = update(&mut state, Message::AddAutostartProfile); } @@ -13022,8 +13101,14 @@ mod tests { ); // Plain Ctrl+C stays an interrupt and Ctrl+V stays normal input. - assert_eq!(terminal_clipboard_action(&key("c"), ctrl, copy, paste), None); - assert_eq!(terminal_clipboard_action(&key("v"), ctrl, copy, paste), None); + assert_eq!( + terminal_clipboard_action(&key("c"), ctrl, copy, paste), + None + ); + assert_eq!( + terminal_clipboard_action(&key("v"), ctrl, copy, paste), + None + ); assert_eq!( terminal_clipboard_action(&key("x"), ctrl | shift, copy, paste), None @@ -13172,6 +13257,53 @@ mod tests { assert!(!super::settings_dirty(&state)); } + #[test] + fn tray_icon_style_changes_wait_for_save_or_undo() { + let mut state = state(); + + let _ = update( + &mut state, + Message::SetTrayIconStyle(super::icons::TrayIconStyle::Monochrome), + ); + assert_eq!(state.tray_icon_style, super::icons::TrayIconStyle::Color); + assert_eq!( + state.tray_icon_style_draft, + super::icons::TrayIconStyle::Monochrome + ); + assert!(super::settings_dirty(&state)); + + let _ = update(&mut state, Message::UndoChanges); + assert_eq!( + state.tray_icon_style_draft, + super::icons::TrayIconStyle::Color + ); + assert!(!super::settings_dirty(&state)); + + let _ = update( + &mut state, + Message::SetTrayIconStyle(super::icons::TrayIconStyle::Monochrome), + ); + super::apply_settings(&mut state); + assert_eq!( + state.tray_icon_style, + super::icons::TrayIconStyle::Monochrome + ); + assert_eq!(state.tray_icon_style_draft, state.tray_icon_style); + } + + #[test] + fn missing_tray_icon_style_defaults_to_color() { + let config: super::ConfigFile = toml::from_str("[general]\nfade_settings = true").unwrap(); + + assert_eq!( + config.general.tray_icon_style, + super::icons::TrayIconStyle::Color + ); + + let text = toml::to_string_pretty(&config).unwrap(); + assert!(text.contains("tray_icon_style = \"color\"")); + } + #[test] fn minimizing_hides_to_tray_only_when_enabled() { let window = test_window(); @@ -14409,11 +14541,7 @@ mod tests { let _ = update(&mut state, Message::ApplyShortcut); assert_eq!( - state - .shortcuts - .close_tab - .as_ref() - .map(ToString::to_string), + state.shortcuts.close_tab.as_ref().map(ToString::to_string), Some("Ctrl+Shift+K".to_owned()) ); assert_eq!( @@ -14655,10 +14783,7 @@ mod tests { assert!(super::settings_dirty(&state)); let _ = update(&mut state, Message::UndoChanges); - assert_eq!( - state.right_click_behavior_draft, - state.right_click_behavior - ); + assert_eq!(state.right_click_behavior_draft, state.right_click_behavior); let _ = update( &mut state, diff --git a/src/tray.rs b/src/tray.rs index da37c70..9e8d183 100644 --- a/src/tray.rs +++ b/src/tray.rs @@ -11,6 +11,8 @@ use iced::futures::StreamExt; use iced::futures::stream::{self, BoxStream}; use tokio::sync::broadcast; +use crate::icons::{self, TrayIconStyle}; + /// Events delivered to the Iced application loop. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Event { @@ -25,8 +27,13 @@ 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() +pub fn start(style: TrayIconStyle) -> Result<(), String> { + imp::start(style) +} + +/// Replaces the icon of the existing tray instance. +pub fn set_icon(style: TrayIconStyle) -> Result<(), String> { + imp::set_icon(style) } /// Releases the tray icon and its menu. Safe to call more than once. @@ -68,7 +75,7 @@ mod imp { 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}; + use super::{EVENTS, Event, QUIT_ID, TOGGLE_ID, TrayIconStyle, broadcast, icons}; thread_local! { // `TrayIcon` is not `Send`; it is created and dropped on the main @@ -77,11 +84,12 @@ mod imp { static TOGGLE_ITEM: RefCell> = const { RefCell::new(None) }; } - pub(super) fn start() -> Result<(), String> { + pub(super) fn start(style: TrayIconStyle) -> Result<(), String> { if EVENTS.get().is_some() { return Ok(()); } + let icon = icons::tray_icon(style)?; let (sender, _) = broadcast::channel(16); // The window starts visible, so the entry starts as "Hide Moorly". @@ -91,18 +99,15 @@ mod imp { let menu = Menu::with_items(&[&toggle, &separator, &quit]) .map_err(|error| format!("Could not build the tray menu: {error}"))?; - let mut builder = TrayIconBuilder::new() + let tray = 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 + .with_menu_on_right_click(true) + .with_icon(icon) .build() .map_err(|error| format!("Could not create the system tray icon: {error}"))?; @@ -135,6 +140,20 @@ mod imp { Ok(()) } + pub(super) fn set_icon(style: TrayIconStyle) -> Result<(), String> { + let icon = icons::tray_icon(style)?; + + TRAY.with(|slot| { + let tray = slot.borrow(); + let Some(tray) = tray.as_ref() else { + return Err("The system tray is not available.".to_owned()); + }; + + tray.set_icon(Some(icon)) + .map_err(|error| format!("Could not update the system tray icon: {error}")) + }) + } + pub(super) fn shutdown() { TOGGLE_ITEM.with(|slot| slot.borrow_mut().take()); TRAY.with(|tray| { @@ -155,30 +174,17 @@ mod imp { } }); } - - #[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> { + use super::TrayIconStyle; + + pub(super) fn start(_style: TrayIconStyle) -> Result<(), String> { + Err("System tray integration is only implemented on Linux and Windows.".to_owned()) + } + + pub(super) fn set_icon(_style: TrayIconStyle) -> Result<(), String> { Err("System tray integration is only implemented on Linux and Windows.".to_owned()) }