Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Closing hides MDM to an icon behind ^ (#545, #534, #527) (#555)

Ahmed Nefzaoui94682b201f5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f2d4db73..2a97fc5b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
- The window no longer freezes when a video or a gallery finishes: marking its files as downloaded from the web, which can wait on the disk and the antivirus for a while with a big video, now happens beside the window ([#510](https://github.com/anefzaoui/misterdownloadmanager/issues/510)).
- Linux: **View → Dark Mode support** turns dark on window managers such as Hyprland and sway when only GNOME's setting says so (`gsettings set org.gnome.desktop.interface color-scheme prefer-dark`), as it did when a desktop portal answered ([#324](https://github.com/anefzaoui/misterdownloadmanager/issues/324)).
- Dark mode no longer draws a bright white line under the menu bar, across the whole window, in the Classic and Native themes ([#379](https://github.com/anefzaoui/misterdownloadmanager/issues/379)).
+- Windows: closing the window hides MDM in the notification area again when Windows keeps its icon among the hidden icons (behind ^), where a new icon goes. MDM took the icon for missing there and left the window in the taskbar instead; it now does that only when Windows has no icon of MDM's at all ([#545](https://github.com/anefzaoui/misterdownloadmanager/issues/545), [#534](https://github.com/anefzaoui/misterdownloadmanager/issues/534), [#527](https://github.com/anefzaoui/misterdownloadmanager/issues/527)).
### Added
- Options → General → **Customize MDM Download panels in browsers**: Export... and Import... for the sites the download button stays off, a plain text file with one site a line ([#424](https://github.com/anefzaoui/misterdownloadmanager/issues/424)).
diff --git a/ROADMAP.md b/ROADMAP.md
index def3f40c..778b5138 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -538,6 +538,11 @@ These ship in a later version, when they're ready.
- 🔄 Add URL's **Use authorization** empty for an address with a login in Options → Sites
Logins, though the download used it
([#511](https://github.com/anefzaoui/misterdownloadmanager/issues/511)): fix in review
+- 🔄 Windows: closing the window left MDM in the taskbar instead of the notification area
+ when its icon was among the hidden icons behind ^
+ ([#545](https://github.com/anefzaoui/misterdownloadmanager/issues/545),
+ [#534](https://github.com/anefzaoui/misterdownloadmanager/issues/534),
+ [#527](https://github.com/anefzaoui/misterdownloadmanager/issues/527)): fix in review
- 🔄 Two tests that fail now and then on busy CI runners
([#518](https://github.com/anefzaoui/misterdownloadmanager/issues/518)): the slow-flush one fixed;
the crash-and-resume one found a real delay in saving a new download's progress, fix in review
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index d28eca64..3add63c1 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -3086,18 +3086,27 @@ impl App {
// off, no tray at all, or Linux with no tray host (#59: a hidden window couldn't come
// back, and one that merely minimized could never be closed).
if !self.exiting && ctx.input(|i| i.viewport().close_requested()) {
- let keep = self.tray.is_some() && self.settings.close_to_tray;
- if keep && self.tray_shown_now() {
- tracing::info!("close: hidden to the notification area");
- ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
- self.hide_to_tray(ctx);
- } else if keep && cfg!(not(target_os = "linux")) {
- tracing::info!("close: no visible tray icon; minimizing to the taskbar");
- ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
- ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
- } else {
- tracing::info!("close: quitting");
- self.exiting = true;
+ use crate::tray::OnClose;
+ let keep = self.settings.close_to_tray;
+ let tray = self.tray.is_some();
+ // The shell is asked afresh, and only when its answer matters.
+ let shown = keep && tray && self.tray_shown_now();
+ let taskbar = cfg!(not(target_os = "linux"));
+ match crate::tray::on_close(keep, tray, shown, taskbar) {
+ OnClose::Hide => {
+ tracing::info!("close: hidden to the notification area");
+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
+ self.hide_to_tray(ctx);
+ }
+ OnClose::Minimize => {
+ tracing::info!("close: no visible tray icon; minimizing to the taskbar");
+ ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
+ }
+ OnClose::Quit => {
+ tracing::info!("close: quitting");
+ self.exiting = true;
+ }
}
}
// Options → General → "Minimize to the notification area" (#63): Minimize hides the
diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs
index 1f8e3832..d5e2aaba 100644
--- a/crates/app/src/tray.rs
+++ b/crates/app/src/tray.rs
@@ -38,6 +38,56 @@ pub fn available() -> bool {
true
}
+/// What the shell says of MDM's icon, asked by [`Tray::visible_now`] (Windows and macOS).
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ShellIcon {
+ /// It says where the icon is (Windows: Shell_NotifyIconGetRect; macOS: the menu bar item's
+ /// frame).
+ pub placed: bool,
+ /// It holds the icon (Windows: `win32::tray_icon_held`), wherever it shows it.
+ pub held: bool,
+}
+
+#[cfg(any(target_os = "windows", target_os = "macos"))]
+impl ShellIcon {
+ /// Whether the icon can bring a hidden window back. One the shell holds is reachable even
+ /// where the shell gives no place for it: the hidden icons behind ^, where Windows puts a
+ /// new icon (#545, #534, #527: MDM took a missing place for a missing icon and left the
+ /// window in the taskbar).
+ pub fn reachable(self) -> bool {
+ self.placed || self.held
+ }
+}
+
+/// What closing the main window does.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OnClose {
+ /// Hidden in the notification area (the menu bar on macOS); downloads go on.
+ Hide,
+ /// Left in the taskbar (the Dock on macOS), minimized: the tray has no icon to come back
+ /// from; downloads go on.
+ Minimize,
+ Quit,
+}
+
+/// What closing the main window does: `keep_running` is Options' "Keep running when closing the
+/// window", `tray` whether a tray object exists, `shown` whether its icon is reachable
+/// ([`ShellIcon::reachable`]; Linux: a tray host runs), `taskbar` whether a window can wait in
+/// the taskbar or the Dock instead (not Linux: #59, a window there that merely minimized could
+/// never be closed). Never a hidden window with no icon to bring it back.
+pub fn on_close(keep_running: bool, tray: bool, shown: bool, taskbar: bool) -> OnClose {
+ if !(keep_running && tray) {
+ OnClose::Quit
+ } else if shown {
+ OnClose::Hide
+ } else if taskbar {
+ OnClose::Minimize
+ } else {
+ OnClose::Quit
+ }
+}
+
/// The longest download name in the tray menu, in characters (the rest ends in "…").
const MENU_NAME_MAX: usize = 48;
@@ -62,6 +112,12 @@ pub struct Tray {
/// shell shouldn't be asked that often (a second of staleness is enough).
#[cfg(any(target_os = "windows", target_os = "macos"))]
visible_checked: std::cell::Cell<Option<(bool, std::time::Instant)>>,
+ /// The shell's last answer, logged when it changes.
+ #[cfg(any(target_os = "windows", target_os = "macos"))]
+ answer: std::cell::Cell<Option<ShellIcon>>,
+ /// The icon's id with the shell, once found (`win32::tray_icon_held`).
+ #[cfg(windows)]
+ icon_id: std::cell::Cell<Option<u32>>,
}
/// A menu entry whose text is translated.
@@ -72,10 +128,31 @@ enum Entry {
}
impl Tray {
- /// Whether the shell is really showing the icon. `tray-icon` ignores a failed
+ /// What the shell says of the icon now.
+ #[cfg(any(target_os = "windows", target_os = "macos"))]
+ fn shell_icon(&self) -> ShellIcon {
+ // MDM_TEST_TRAY_RECT=0: the shell gives no place for the icon, as the reporters' did for
+ // one behind ^ (the close test, with a real icon the shell holds).
+ let placed = self.tray.rect().is_some()
+ && std::env::var_os("MDM_TEST_TRAY_RECT").is_none_or(|v| v != "0");
+ #[cfg(windows)]
+ let held = {
+ let id = crate::win32::tray_icon_held(self.tray.window_handle(), self.icon_id.get());
+ if id.is_some() {
+ self.icon_id.set(id);
+ }
+ id.is_some()
+ };
+ // macOS has no other question: the menu bar item's frame is the answer.
+ #[cfg(not(windows))]
+ let held = false;
+ ShellIcon { placed, held }
+ }
+
+ /// Whether the shell really has the icon, to click. `tray-icon` ignores a failed
/// `Shell_NotifyIcon(NIM_ADD)` (it waits for the taskbar to be recreated), so `Tray::new`
- /// returning `Some` doesn't mean the user can see or click the icon. Asking for its rect is
- /// the only way to know. Linux has no such query: its [`available`] stands for it.
+ /// returning `Some` doesn't mean the user can see or click the icon: the shell is asked
+ /// ([`ShellIcon`]). Linux has no such query: its [`available`] stands for it.
#[cfg(any(target_os = "windows", target_os = "macos"))]
pub fn visible(&self) -> bool {
// Off-screen tests can't make the shell answer reliably: the variable says what to
@@ -98,7 +175,15 @@ impl Tray {
if let Some(v) = std::env::var_os("MDM_TEST_TRAY_VISIBLE") {
return v == "1";
}
- let shown = self.tray.rect().is_some();
+ let icon = self.shell_icon();
+ if self.answer.replace(Some(icon)) != Some(icon) {
+ tracing::info!(
+ "tray icon: placed {}, held by the shell {}",
+ icon.placed,
+ icon.held
+ );
+ }
+ let shown = icon.reachable();
self.visible_checked
.set(Some((shown, std::time::Instant::now())));
shown
@@ -233,6 +318,10 @@ impl Tray {
labels,
#[cfg(any(target_os = "windows", target_os = "macos"))]
visible_checked: Default::default(),
+ #[cfg(any(target_os = "windows", target_os = "macos"))]
+ answer: Default::default(),
+ #[cfg(windows)]
+ icon_id: Default::default(),
})
}
@@ -329,6 +418,51 @@ fn picture() -> Result<tray_icon::Icon, String> {
mod tests {
use super::*;
+ /// The close decision without a shell (#545, #534, #527), with the shell's answers as
+ /// Windows gives them. Measured on Windows 11 (build 26200), a new icon behind ^: placed (the
+ /// rect of ^ itself) and held; the same icon once removed: neither. The reporters' Windows
+ /// (10 and 11) gave an icon behind ^ no place: the icon there, the window left in the taskbar.
+ #[cfg(any(target_os = "windows", target_os = "macos"))]
+ #[test]
+ fn closing_hides_to_an_icon_the_shell_holds_even_with_no_place() {
+ let held_no_place = ShellIcon {
+ placed: false,
+ held: true,
+ };
+ let held_placed = ShellIcon {
+ placed: true,
+ held: true,
+ };
+ let none = ShellIcon {
+ placed: false,
+ held: false,
+ };
+ for icon in [held_no_place, held_placed] {
+ assert!(icon.reachable(), "{icon:?}");
+ assert_eq!(on_close(true, true, icon.reachable(), true), OnClose::Hide);
+ }
+ // No icon the shell holds (Explorer not running, the icon refused or lost): the
+ // taskbar, never a hidden window with no way back.
+ assert!(!none.reachable());
+ assert_eq!(
+ on_close(true, true, none.reachable(), true),
+ OnClose::Minimize
+ );
+ }
+
+ /// The rest of the close decision, on every system (#457, #59).
+ #[test]
+ fn closing_quits_with_the_option_off_no_tray_or_nowhere_to_wait() {
+ // No icon and no taskbar to wait in (Linux with no tray host): quit.
+ assert_eq!(on_close(true, true, false, false), OnClose::Quit);
+ assert_eq!(on_close(true, true, true, false), OnClose::Hide);
+ // The option off, or no tray object at all: closing quits, whatever the shell says.
+ for shown in [true, false] {
+ assert_eq!(on_close(false, true, shown, true), OnClose::Quit);
+ assert_eq!(on_close(true, false, shown, true), OnClose::Quit);
+ }
+ }
+
#[test]
fn menu_names_are_shortened_and_keep_their_ampersands() {
assert_eq!(short("a & b.zip"), "a && b.zip");
diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rs
index de0349bf..60c9350c 100644
--- a/crates/app/src/win32.rs
+++ b/crates/app/src/win32.rs
@@ -1632,6 +1632,42 @@ pub fn main_minimize_to_tray(ctx: &egui::Context, enabled: bool) -> bool {
})
}
+/// The highest icon id [`tray_icon_held`] tries. tray-icon gives each icon an id of its own
+/// from a counter it shares with its icon names, and doesn't say which (a program's first icon
+/// has 2).
+const TRAY_ICON_IDS: u32 = 16;
+
+/// Whether the shell holds a notification-area icon of `hwnd` (the tray's own hidden window,
+/// which has one icon), and its id: `known` first, else each id up to [`TRAY_ICON_IDS`]. An
+/// empty `NIM_MODIFY` changes nothing and succeeds only for an icon the shell has, wherever it
+/// shows it: in the taskbar or in the hidden icons behind ^. Shell_NotifyIconGetRect isn't
+/// enough: it can fail for an icon behind ^ (#545, #534, #527: Windows 10 and 11, the icon
+/// there and MDM sure it had none; Windows 11 build 26200 gives such an icon the rect of ^
+/// itself). This fails, as that does, when Explorer isn't running or the icon was refused or
+/// lost.
+pub fn tray_icon_held(hwnd: HWND, known: Option<u32>) -> Option<u32> {
+ use windows_sys::Win32::UI::Shell::{NIM_MODIFY, NOTIFYICONDATAW, Shell_NotifyIconW};
+ let held = |id: u32| {
+ let nid = NOTIFYICONDATAW {
+ cbSize: size_of::<NOTIFYICONDATAW>() as u32,
+ hWnd: hwnd,
+ uID: id,
+ uFlags: 0,
+ // SAFETY: a plain C struct; all zero is its empty value.
+ ..unsafe { zeroed() }
+ };
+ // SAFETY: nid lives for the call; the shell only reads it.
+ unsafe { Shell_NotifyIconW(NIM_MODIFY, &nid) != 0 }
+ };
+ if hwnd.is_null() {
+ return None;
+ }
+ known
+ .into_iter()
+ .chain(1..=TRAY_ICON_IDS)
+ .find(|id| held(*id))
+}
+
/// What a borderless window of ours is, for [`popup_window`]: every one is a plain popup
/// ([`popup_style`], #208); they differ in how they take the pointer and how they look.
#[derive(Clone, Copy, Debug, PartialEq)]
diff --git a/crates/app/tests/close_without_tray.rs b/crates/app/tests/close_without_tray.rs
index 17d560b0..2abaca6a 100644
--- a/crates/app/tests/close_without_tray.rs
+++ b/crates/app/tests/close_without_tray.rs
@@ -2,8 +2,9 @@
//! off quits; on hides; on with no visible icon minimizes to the taskbar instead (downloads
//! continue, and the window stays reachable); with no tray at all it quits, as ever. The real app,
//! off the screens, with data folders of its own; a tray object whose visibility
-//! MDM_TEST_TRAY_VISIBLE decides, or no tray object. Windows only (WM_CLOSE), so it runs on
-//! request:
+//! MDM_TEST_TRAY_VISIBLE decides, or no tray object; and a real icon, the shell asked for real,
+//! hides the window even when the shell gives it no place (an icon behind ^, #545). Windows only
+//! (WM_CLOSE), so it runs on request:
//! `cargo test -p mdm-app --test close_without_tray -- --ignored`.
#![cfg(windows)]
@@ -225,3 +226,55 @@ fn closing_follows_the_option_and_the_tray_icon() {
assert!(status.success(), "{status}");
assert!(log(&data4).contains("close: quitting"), "{}", log(&data4));
}
+
+/// The app's environment with its real tray icon, the shell asked for real; `placed` false says
+/// the shell gives the icon no place (MDM_TEST_TRAY_RECT=0), as the reporters' did for an icon
+/// behind ^ (#545, #534, #527).
+fn env_real<'a>(cmd: &'a mut Command, data: &Path, placed: bool) -> &'a mut Command {
+ cmd.env("MDM_DATA_DIR", data)
+ .env("MDM_OFFSCREEN", "1")
+ .env("MDM_TEST_TRAY", "1")
+ .env("MDM_TEST_TRAY_RECT", if placed { "1" } else { "0" })
+}
+
+/// Closing with a real icon the shell holds: hidden there, whether or not the shell says where
+/// the icon is (a new icon goes behind ^, where the shell may give it none). The shell is this
+/// machine's: its icon is added for the test and removed when the app exits.
+#[test]
+#[ignore = "opens the app's windows (off-screen) and a tray icon: run with --ignored"]
+fn closing_hides_to_an_icon_the_shell_holds() {
+ let dir = tempfile::tempdir().unwrap();
+ let wait = Duration::from_secs(60);
+ for (name, placed) in [("placed", true), ("no-place", false)] {
+ let data = data(dir.path(), name, true);
+ let mut app = Process(
+ env_real(&mut Command::new(APP), &data, placed)
+ .spawn()
+ .unwrap(),
+ );
+ wait_for(&mut app, &data, "first frame drawn", wait);
+ wait_for(&mut app, &data, "tray icon shown", wait);
+ assert!(close_main(app.id()), "no main window to close");
+ wait_for(
+ &mut app,
+ &data,
+ "close: hidden to the notification area",
+ Duration::from_secs(10),
+ );
+ let text = log(&data);
+ assert!(
+ text.contains(&format!(
+ "tray icon: placed {placed}, held by the shell true"
+ )),
+ "{text}"
+ );
+ assert!(
+ app.try_wait().unwrap().is_none(),
+ "the app quit instead of hiding"
+ );
+ let _ = env_real(&mut Command::new(APP), &data, placed)
+ .arg("/exit")
+ .status();
+ let _ = wait_exit(&mut app, Duration::from_secs(20));
+ }
+}