misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Windows: Close hides MDM in the notification area again, and the tray icon's questions leave the window's thread (#750, #747) (#764)
Ahmed Nefzaoui6b4a76255e3c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex af7dec8a..2cf1bb8e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -64,7 +64,8 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see- 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: a download's progress window with a title of 256 characters or more (a torrent with a long name, or a file name kept whole in a folder too deep to shorten it) has MDM's own title bar again, instead of the system's drawn above it (part of [#540](https://github.com/anefzaoui/misterdownloadmanager/issues/540)).-- 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)).+- Windows: closing the window hides MDM in the notification area again, as it did before 0.5.2, instead of leaving it minimized in the taskbar with its icon right there, among the hidden icons behind ^ (where Windows puts a new icon). Before hiding the window, MDM asked Windows where the icon was, and Windows 10 and some Windows 11 versions give an icon behind ^ no place; MDM took that for no icon at all. It now also asks whether Windows has the icon, wherever it shows it, and keeps the window in the taskbar only when Windows says it has none (Explorer isn't running, or the icon was lost): when Windows doesn't answer, the window hides as usual, and starting MDM again always brings it back. The same goes for **Minimize to the notification area**, and for a start with Windows, which no longer shows the window minimized after half a minute ([#750](https://github.com/anefzaoui/misterdownloadmanager/issues/750), [#718](https://github.com/anefzaoui/misterdownloadmanager/issues/718), [#754](https://github.com/anefzaoui/misterdownloadmanager/issues/754), [#545](https://github.com/anefzaoui/misterdownloadmanager/issues/545), [#534](https://github.com/anefzaoui/misterdownloadmanager/issues/534), [#527](https://github.com/anefzaoui/misterdownloadmanager/issues/527)).+- Windows: the window no longer freezes while Explorer is slow to answer about MDM's notification-area icon ("freeze in misterdownloadmanager::tray::Tray::visible_now"). The window asked Explorer about the icon every second, and set the icon's tip, on its own thread, and waited as long as Explorer took: 8 seconds in the report. Both now happen beside the window, which goes by Windows' last answer; an answer that is late or missing is never taken for "no icon", so a window in the notification area stays there ([#747](https://github.com/anefzaoui/misterdownloadmanager/issues/747); thanks to [@TG-Twilight](https://github.com/TG-Twilight) for the first version, [#697](https://github.com/anefzaoui/misterdownloadmanager/pull/697)).- The browser's **video button** over YouTube's thumbnail previews keeps one place, so it can be clicked: it moved to another corner when the preview showed its sound and captions buttons, back when they hid as the pointer reached it, and away again, and it followed the preview as it shrank. Over the same video it now only moves on to a free corner, never back, and it stays put while the pointer is on it ([#560](https://github.com/anefzaoui/misterdownloadmanager/issues/560)).- Chrome, Edge, Brave and the other Chromium browsers: a download the extension leaves to the browser keeps the name and folder another extension gives it (Save In's folders, or any extension's own download into a folder). The extension's answer for it counted as a name of its own, an empty one, and when the extension was the newest installed it won: the file landed in the Downloads folder, and the browser could warn of a conflict between the two extensions ([#578](https://github.com/anefzaoui/misterdownloadmanager/issues/578)).- Windows: fewer freezes ("The window stopped responding") on a system held up by its disk or its memory. Every 2 seconds, and in each frame of an open dialog, MDM asked Windows about its windows' title bar colours, and the window waited with Windows' answer; it now sets a title bar's light or dark once, when the window opens or the theme changes. Looking for its own windows no longer waits on another busy part of MDM either ([#633](https://github.com/anefzaoui/misterdownloadmanager/issues/633), [#583](https://github.com/anefzaoui/misterdownloadmanager/issues/583)).diff --git a/ROADMAP.md b/ROADMAP.mdindex ffc82f69..f31b7200 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -671,11 +671,15 @@ These ship in a later version, when they're ready.- 🔄 Add URL's **Use authorization** empty for an address with a login in Options → SitesLogins, 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+- 🔄 Windows: closing the window left MDM minimized in the taskbar instead of the notification+ area while its icon was there, among the hidden icons behind ^ (0.5.2;+ [#750](https://github.com/anefzaoui/misterdownloadmanager/issues/750), [#718](https://github.com/anefzaoui/misterdownloadmanager/issues/718),+ [#754](https://github.com/anefzaoui/misterdownloadmanager/issues/754), [#545](https://github.com/anefzaoui/misterdownloadmanager/issues/545),+ [#534](https://github.com/anefzaoui/misterdownloadmanager/issues/534), [#527](https://github.com/anefzaoui/misterdownloadmanager/issues/527)): MDM+ now keeps the window in the taskbar only when Windows says it has no icon of MDM's, not when+ Windows can't say where the icon is; fix in review, to confirm on Windows 10+- 🔄 The window freezing while Explorer was slow to answer about MDM's notification-area icon+ ([#747](https://github.com/anefzaoui/misterdownloadmanager/issues/747)): asked beside the window now; 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 onenow measures the transfer instead of how fast the runner's disk takes in the file (Windowsdiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 0980df25..f7424b8e 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -3411,26 +3411,36 @@ impl App {}}- /// Whether the tray icon is shown somewhere (Linux: a tray host is there; asked when the- /// window is closed, the host may come and go). On Windows and macOS the icon itself is- /// asked: the shell can accept it and still show nothing, and a window hidden with no icon- /// to click has no way back. Cached for the per-frame minimize path.- fn tray_shown(&self) -> bool {+ /// What the shell says of the tray icon (Linux: there when a tray host is, asked each time:+ /// the host may come and go). On Windows and macOS the icon itself is asked: the shell can+ /// accept it and still show nothing, and a window hidden with no icon to click has no way+ /// back. Windows' answer comes from a thread of its own and is never waited for (#747);+ /// macOS's is a second old at most, for the per-frame minimize path.+ fn tray_icon(&self) -> crate::tray::Icon {#[cfg(any(target_os = "windows", target_os = "macos"))]if let Some(tray) = &self.tray {- return tray.visible();+ return tray.icon();}- crate::tray::available()+ Self::tray_host()}- /// [`tray_shown`] without the cache, for the close decision: an icon can disappear between- /// the cached answer and the close, and hiding then would be a ghost window.- fn tray_shown_now(&self) -> bool {+ /// [`tray_icon`] for the close decision: on macOS asked afresh, as an icon can disappear+ /// between the cached answer and the close, and hiding then would be a ghost window.+ fn tray_icon_now(&self) -> crate::tray::Icon {#[cfg(any(target_os = "windows", target_os = "macos"))]if let Some(tray) = &self.tray {- return tray.visible_now();+ return tray.icon_now();+ }+ Self::tray_host()+ }++ /// Whether a tray shows icons at all, as [`crate::tray::available`] says.+ fn tray_host() -> crate::tray::Icon {+ if crate::tray::available() {+ crate::tray::Icon::There+ } else {+ crate::tray::Icon::Gone}- crate::tray::available()}/// Started with the session (#226): once a second, until it is known, where the window goes@@ -3452,7 +3462,8 @@ impl App {}let icon = self.at_login_icon.map(|t| t.elapsed());let since = started.elapsed();- match at_login(since, icon, icon.is_some() && self.tray_shown()) {+ let shown = icon.is_some() && self.tray_icon() == crate::tray::Icon::There;+ match at_login(since, icon, shown) {AtLogin::Wait => {}AtLogin::Tray => {tracing::info!(@@ -3514,6 +3525,21 @@ impl App {t.set_downloads(&running);}self.settle_at_login(ctx);+ // Hidden in the notification area, and the shell, running and answering, has said for+ // some seconds that it has no icon of MDM's (lost, and not added back): the window comes+ // back to the taskbar, minimized. Never on no answer, or while Explorer isn't running+ // (it gives the icon back as it starts again).+ #[cfg(windows)]+ if self.hidden && self.at_login.is_none() && self.tray.as_ref().is_some_and(|t| t.rescue())+ {+ tracing::info!(+ "hidden, and the shell has no tray icon of MDM's: back in the taskbar, minimized"+ );+ self.hidden = false;+ self.trim_when_hidden = None;+ ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));+ }// When the window was last focused, for Toggle below. Kept every frame:// by the time a tray click arrives the taskbar already took the focus.if ctx.input(|i| i.viewport().focused) == Some(true) {@@ -3568,9 +3594,10 @@ impl App {};self.run(cmd, None, ctx);}- // Closing hides the window in the tray; downloads and queues go on. With no icon the shell- // shows (Windows, macOS: a tray that exists but says it has none) the window goes to the- // taskbar or the Dock instead: still reachable, downloads still going. Everywhere else+ // Closing hides the window in the tray; downloads and queues go on. When the shell says it+ // has no icon (Windows, macOS: a tray that exists, and the shell says it has none) the+ // window goes to the taskbar or the Dock instead: still reachable, downloads still going.+ // No answer from the shell is not such a "no" (#750, `tray::on_close`). Everywhere else// closing closes, as any window's does: Options' "Keep running when closing the window"// 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).@@ -3578,12 +3605,16 @@ impl App {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();+ // The shell's answer, only when it matters (macOS: asked afresh).+ let icon = if keep && tray {+ self.tray_icon_now()+ } else {+ crate::tray::Icon::Gone+ };let taskbar = cfg!(not(target_os = "linux"));- match crate::tray::on_close(keep, tray, shown, taskbar) {+ match crate::tray::on_close(keep, tray, icon, taskbar) {OnClose::Hide => {- tracing::info!("close: hidden to the notification area");+ tracing::info!("close: hidden to the notification area (tray icon: {icon:?})");ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);self.hide_to_tray(ctx);}@@ -3609,7 +3640,7 @@ impl App {&& self.settings.minimize_to_tray&& can_hide&& !self.exiting- && self.tray_shown();+ && self.tray_icon() != crate::tray::Icon::Gone;// Windows: the minimize command itself is caught (win32), so the window goes straight to// the tray, never minimized (an idle app runs no frame while minimized: it wouldn't see).#[cfg(windows)]diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rsindex 4762c137..a1e45bd2 100644--- a/crates/app/src/tray.rs+++ b/crates/app/src/tray.rs@@ -7,6 +7,10 @@use std::sync::mpsc::{Receiver, Sender, channel};use std::sync::{Arc, Mutex};+mod watch;++pub use watch::Icon;+use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem, Submenu,};@@ -42,28 +46,6 @@ 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 {@@ -76,14 +58,20 @@ pub enum OnClose {}/// 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 {+/// window", `tray` whether a tray object exists, `icon` what the shell last said of its icon+/// ([`Tray::icon`]; Linux: there when 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: the taskbar (or quitting) only when the+/// shell said the icon is gone. No answer, or an old one, hides the window as an icon that is+/// there does (#750, #718, #754: a shell that couldn't confirm the icon left the window in the+/// taskbar with the icon right there); such a window still comes back from the icon once the+/// shell answers, and a second start of MDM always brings it back.+pub fn on_close(keep_running: bool, tray: bool, icon: Icon, taskbar: bool) -> OnClose {if !(keep_running && tray) {OnClose::Quit- } else if shown {+ } else if icon != Icon::Gone {OnClose::Hide} else if taskbar {OnClose::Minimize@@ -102,6 +90,9 @@ pub struct Tray {start_queue: MenuItem,stop_queue: MenuItem,queue_running: std::cell::Cell<Option<bool>>,+ /// The icon itself, kept for as long as the tray (Windows asks and tells the shell about it+ /// from the watcher's thread, through its hidden window).+ #[cfg_attr(windows, allow(dead_code))]tray: TrayIcon,/// The tip shown and when, so the shell is told at most once a second.tip: std::cell::RefCell<(String, Option<std::time::Instant>)>,@@ -112,16 +103,20 @@ pub struct Tray {download_ids: Arc<Mutex<Vec<(MenuId, u64)>>>,/// Every entry with its English text, to translate again when the language changes.labels: Vec<(Entry, &'static str)>,- /// What [`Tray::visible`] last saw and when: the minimize path asks every frame, and the- /// 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`).+ /// What [`Tray::icon`] last saw and when: the minimize path asks every frame, and the menu+ /// bar shouldn't be asked that often (a second of staleness is enough).+ #[cfg(target_os = "macos")]+ visible_checked: std::cell::Cell<Option<(Icon, std::time::Instant)>>,+ /// The menu bar's last answer, logged when it changes.+ #[cfg(target_os = "macos")]+ answer: std::cell::Cell<Option<bool>>,+ /// The thread that asks the shell about the icon and sets its tip (#747: never the window's).+ #[cfg(windows)]+ watch: watch::Watch,+ /// The last answer the window took from it, for a frame where the watcher is busy writing+ /// the next.#[cfg(windows)]- icon_id: std::cell::Cell<Option<u32>>,+ seen: std::cell::Cell<Option<watch::Seen>>,}/// A menu entry whose text is translated.@@ -132,65 +127,69 @@ enum Entry {}impl Tray {- /// What the shell says of the icon now.+ /// What the shell says of the icon, as the window may act on it: closing, Minimize to the+ /// notification area and the start with the session ask it every frame. Windows: the last+ /// answer of the watcher's thread, never waiting for the shell; macOS: the menu bar item's+ /// frame (AppKit's, asked on the window's thread), a second old at most. Linux has no such+ /// question: its [`available`] stands for it.#[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");+ pub fn icon(&self) -> Icon {+ if let Some(v) = test_visible() {+ return v;+ }#[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);+ return watch::icon(self.seen(), std::time::Instant::now());+ #[cfg(target_os = "macos")]+ {+ if let Some((icon, checked)) = self.visible_checked.get()+ && checked.elapsed() < std::time::Duration::from_secs(1)+ {+ return icon;}- 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 }+ self.icon_now()+ }}- /// 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: the shell is asked- /// ([`ShellIcon`]). Linux has no such query: its [`available`] stands for it.+ /// [`Tray::icon`], for closing: on macOS without the one-second cache (an icon gone since must+ /// not hide the window); on Windows the same last answer, whose age it weighs.#[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- // answer (the startup tray test uses it with MDM_TEST_TRAY).- if let Some(v) = std::env::var_os("MDM_TEST_TRAY_VISIBLE") {- return v == "1";+ pub fn icon_now(&self) -> Icon {+ if let Some(v) = test_visible() {+ return v;}- if let Some((shown, checked)) = self.visible_checked.get()- && checked.elapsed() < std::time::Duration::from_secs(1)+ #[cfg(windows)]+ return self.icon();+ #[cfg(target_os = "macos")]{- return shown;+ // MDM_TEST_TRAY_RECT=0: the menu bar gives the item no place.+ let placed = self.tray.rect().is_some()+ && std::env::var_os("MDM_TEST_TRAY_RECT").is_none_or(|v| v != "0");+ if self.answer.replace(Some(placed)) != Some(placed) {+ tracing::info!("tray icon: placed {placed}");+ }+ let icon = if placed { Icon::There } else { Icon::Gone };+ self.visible_checked+ .set(Some((icon, std::time::Instant::now())));+ icon}- self.visible_now()}- /// [`visible`] without the one-second cache: closing asks once and must not use an answer- /// from before the icon went away.- #[cfg(any(target_os = "windows", target_os = "macos"))]- pub fn visible_now(&self) -> bool {- if let Some(v) = std::env::var_os("MDM_TEST_TRAY_VISIBLE") {- return v == "1";- }- 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- );+ /// Whether a window hidden in the notification area should come back to the taskbar: the+ /// shell, running and answering, has said for some seconds that it has no icon of MDM's+ /// (`watch::rescue`). Never on no answer. Windows only: macOS leaves a window hidden in the+ /// menu bar as it was.+ #[cfg(windows)]+ pub fn rescue(&self) -> bool {+ test_visible().is_none() && watch::rescue(self.seen(), std::time::Instant::now())+ }++ /// The watcher's last answer, or the one the window took before while it is busy writing.+ #[cfg(windows)]+ fn seen(&self) -> Option<watch::Seen> {+ if let Some(seen) = self.watch.latest() {+ self.seen.set(Some(seen));}- let shown = icon.reachable();- self.visible_checked- .set(Some((shown, std::time::Instant::now())));- shown+ self.seen.get()}/// The icon and its menu; events wake `ctx`. None if the shell refuses the icon (logged).@@ -269,6 +268,22 @@ impl Tray {}};+ // Only the hidden window's handle crosses to the watcher's thread: TrayIcon stays here.+ #[cfg(windows)]+ let watch = {+ let wake = ctx.clone();+ watch::Watch::new(+ WindowsShell {+ hwnd: tray.window_handle() as isize,+ id: None,+ // MDM_TEST_TRAY_RECT=0: the shell gives the icon no place, as the reporters'+ // did for one behind ^ (the close test, with a real icon the shell holds).+ rect_withheld: std::env::var_os("MDM_TEST_TRAY_RECT").is_some_and(|v| v == "0"),+ },+ move || wake.request_repaint(),+ )+ };+let (tx, rx) = channel();let wake = |tx: &Sender<TrayCmd>, ctx: &egui::Context| (tx.clone(), ctx.clone());let (icon_tx, icon_ctx) = wake(&tx, ctx);@@ -320,12 +335,14 @@ impl Tray {shown_downloads: Default::default(),download_ids,labels,- #[cfg(any(target_os = "windows", target_os = "macos"))]+ #[cfg(target_os = "macos")]visible_checked: Default::default(),- #[cfg(any(target_os = "windows", target_os = "macos"))]+ #[cfg(target_os = "macos")]answer: Default::default(),#[cfg(windows)]- icon_id: Default::default(),+ watch,+ #[cfg(windows)]+ seen: Default::default(),})}@@ -362,6 +379,12 @@ impl Tray {.1.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(1));if last.0 != tip && due {+ // Windows: the watcher's thread sets it, as setting it waits for Explorer (#747).+ #[cfg(windows)]+ if !self.watch.tip(tip) {+ return;+ }+ #[cfg(not(windows))]let _ = self.tray.set_tooltip(Some(tip));*last = (tip.to_owned(), Some(std::time::Instant::now()));}@@ -396,6 +419,49 @@ impl Tray {}}+/// What the tests say of the icon, as off-screen tests can't make the shell answer reliably+/// (MDM_TEST_TRAY_VISIBLE: 1 there, anything else gone; the startup and close tests use it with+/// MDM_TEST_TRAY).+#[cfg(any(target_os = "windows", target_os = "macos"))]+fn test_visible() -> Option<Icon> {+ std::env::var_os("MDM_TEST_TRAY_VISIBLE")+ .map(|v| if v == "1" { Icon::There } else { Icon::Gone })+}++/// Windows' shell, as the watcher's thread asks it: the tray's hidden window (one icon) and the+/// icon's id once found.+#[cfg(windows)]+struct WindowsShell {+ hwnd: isize,+ id: Option<u32>,+ rect_withheld: bool,+}++#[cfg(windows)]+impl watch::Port for WindowsShell {+ fn ask(&mut self) -> watch::Shell {+ use crate::win32::TrayAnswer;+ match crate::win32::tray_icon_ask(self.hwnd, self.id, self.rect_withheld) {+ TrayAnswer::NoTaskbar => watch::Shell::NoTaskbar,+ TrayAnswer::Silent => watch::Shell::Silent,+ TrayAnswer::Answered { held, placed } => {+ if held.is_some() {+ self.id = held;+ }+ watch::Shell::Answered {+ placed,+ held: held.is_some(),+ }+ }+ }+ }++ fn tip(&mut self, tip: &str) -> bool {+ self.id+ .is_some_and(|id| crate::win32::tray_icon_tip(self.hwnd, id, tip))+ }+}+/// A download's name as the tray menu shows it: at most MENU_NAME_MAX characters, the rest "…";/// "&" doubled, which menus would read as a shortcut mark.fn short(name: &str) -> String {@@ -422,48 +488,26 @@ 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"))]+ /// The close decision (#750, #718, #754, #545): an icon the shell says is there, or no answer+ /// at all, hides the window; only the shell saying the icon is gone leaves it in the taskbar.#[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);+ fn closing_hides_unless_the_shell_says_the_icon_is_gone() {+ for icon in [Icon::There, Icon::Unknown] {+ assert_eq!(on_close(true, true, icon, true), OnClose::Hide, "{icon:?}");}- // 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- );+ assert_eq!(on_close(true, true, Icon::Gone, 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);+ assert_eq!(on_close(true, true, Icon::Gone, false), OnClose::Quit);+ assert_eq!(on_close(true, true, Icon::There, 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);+ for icon in [Icon::There, Icon::Unknown, Icon::Gone] {+ assert_eq!(on_close(false, true, icon, true), OnClose::Quit);+ assert_eq!(on_close(true, false, icon, true), OnClose::Quit);}}diff --git a/crates/app/src/tray/watch.rs b/crates/app/src/tray/watch.rsnew file mode 100644index 00000000..d65e943b--- /dev/null+++ b/crates/app/src/tray/watch.rs@@ -0,0 +1,544 @@+//! What the shell says of MDM's notification-area icon, asked off the window's thread (#747).+//! Windows' questions about an icon wait for Explorer: for seconds when it is busy (8 s in #747,+//! the window frozen meanwhile). So a thread of its own asks ([`Watch`]), every [`EVERY`], and+//! sets the icon's tip too; the window takes the last answer ([`Watch::latest`]), which never+//! waits, and is woken when it changes. The rule of the clipboard's reads (`clipboard.rs`) and the+//! torrents' numbers (#693).+//!+//! No answer is not an answer: none yet, one too old ([`STALE`]: the shell stopped answering) or+//! one being written as the window looks ([`Icon::Unknown`]) never decides that the icon is gone.+//! Only the shell saying so does ([`Icon::Gone`]): no taskbar at all (Explorer isn't running), or+//! a taskbar that answers and has no icon of MDM's, in any place. A window hidden while the answer+//! is unknown can still come back: from the icon once it answers, and a second start of MDM always+//! brings the window back (`App::handle_command`).++// The watcher asks Windows' shell; elsewhere only the answers' meaning is used (macOS asks the+// menu bar on the window's thread, which AppKit wants; Linux asks whether a tray host runs).+#![cfg_attr(not(windows), allow(dead_code))]++use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, TryLockError};+use std::time::{Duration, Instant};++/// How often the shell is asked.+pub const EVERY: Duration = Duration::from_secs(2);++/// An answer this old, from when its question was put, is no answer: the shell has been slow to+/// give the next (three questions' time).+pub const STALE: Duration = Duration::from_secs(6);++/// How long a running shell must have said, answer after answer, that it has no icon of MDM's+/// before a window hidden in the notification area comes back to the taskbar: longer than+/// Explorer takes to start again and be given the icon back (`TaskbarCreated`).+pub const RESCUE_AFTER: Duration = Duration::from_secs(10);++/// One answer of the shell.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Shell {+ /// No taskbar: Explorer isn't running (or a shell without a notification area is).+ NoTaskbar,+ /// The taskbar is there and didn't answer (it stopped responding, or the question timed out).+ Silent,+ /// The shell answered: whether it gives the icon a place on screen, and whether it holds it+ /// (an icon among the hidden ones behind ^ may have no place, and is held all the same).+ Answered { placed: bool, held: bool },+}++impl Shell {+ /// Whether this answer says the icon isn't there.+ fn says_gone(self) -> bool {+ matches!(+ self,+ Shell::NoTaskbar+ | Shell::Answered {+ placed: false,+ held: false+ }+ )+ }+}++/// What the window makes of the shell's last answer.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Icon {+ /// The shell holds the icon, or gives it a place: it can bring a hidden window back.+ There,+ /// No answer, or none recent: nothing is concluded either way.+ Unknown,+ /// The shell said it has no icon of MDM's, or there is no taskbar.+ Gone,+}++/// The shell's last answer, when its question was put, and since when every answer in a row said+/// the icon is gone.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Seen {+ pub shell: Shell,+ pub asked: Instant,+ pub gone_since: Option<Instant>,+}++/// What `seen` (the last answer the window has, if any) says at `now`.+pub fn icon(seen: Option<Seen>, now: Instant) -> Icon {+ let Some(seen) = seen else {+ return Icon::Unknown;+ };+ if now.saturating_duration_since(seen.asked) >= STALE {+ return Icon::Unknown;+ }+ match seen.shell {+ Shell::Silent => Icon::Unknown,+ Shell::Answered { placed, held } if placed || held => Icon::There,+ Shell::NoTaskbar | Shell::Answered { .. } => Icon::Gone,+ }+}++/// Whether a window hidden in the notification area comes back to the taskbar (minimized): only+/// once a running shell has said for [`RESCUE_AFTER`] that it has no icon of MDM's. Never on no+/// answer, an old one, or while there is no taskbar: Explorer gives the icon back as it starts+/// again, and a window brought out then would only be in the way.+pub fn rescue(seen: Option<Seen>, now: Instant) -> bool {+ icon(seen, now) == Icon::Gone+ && seen.is_some_and(|s| {+ matches!(s.shell, Shell::Answered { .. })+ && s.gone_since+ .is_some_and(|t| now.saturating_duration_since(t) >= RESCUE_AFTER)+ })+}++/// The shell, as the watcher's thread asks it (Windows: `win32::tray_icon_ask`; tests: a fake).+pub trait Port: Send + 'static {+ /// Ask about the icon (it may wait, for ever).+ fn ask(&mut self) -> Shell;+ /// Set the icon's tip; false if the shell didn't take it.+ fn tip(&mut self, tip: &str) -> bool;+}++/// The thread that asks the shell; the window reads its last answer.+pub struct Watch {+ shared: Arc<Shared>,+}++struct Shared {+ state: Mutex<State>,+ /// A new tip to set, or the watch closed.+ told: Condvar,+}++#[derive(Default)]+struct State {+ seen: Option<Seen>,+ /// The tip the window wants, and its number (one more for each).+ tip: Option<String>,+ tip_number: u64,+ closed: bool,+}++impl Shared {+ fn lock(&self) -> MutexGuard<'_, State> {+ self.state.lock().unwrap_or_else(PoisonError::into_inner)+ }++ /// The state if nobody holds it: the window never waits, even for the watcher's short write.+ fn try_lock(&self) -> Option<MutexGuard<'_, State>> {+ match self.state.try_lock() {+ Ok(s) => Some(s),+ Err(TryLockError::Poisoned(p)) => Some(p.into_inner()),+ Err(TryLockError::WouldBlock) => None,+ }+ }+}++impl Watch {+ /// Ask `port` now and every [`EVERY`] on a thread of its own; `wake` is told when an answer+ /// differs from the one before.+ pub fn new(port: impl Port, wake: impl Fn() + Send + 'static) -> Watch {+ Watch::every(EVERY, port, wake)+ }++ /// [`Watch::new`], asking every `every`.+ fn every(every: Duration, mut port: impl Port, wake: impl Fn() + Send + 'static) -> Watch {+ let shared = Arc::new(Shared {+ state: Mutex::new(State::default()),+ told: Condvar::new(),+ });+ let worker = shared.clone();+ let spawned = std::thread::Builder::new()+ .name("tray icon".into())+ .spawn(move || {+ let mut next = Instant::now();+ let mut last: Option<Shell> = None;+ let mut gone_since: Option<Instant> = None;+ // The tip's number the shell has, if it has the current one.+ let mut set: Option<u64> = None;+ loop {+ if Instant::now() >= next {+ // Dated from the question: an answer that took long is already old.+ let asked = Instant::now();+ // Not under the lock: the window never waits for the shell.+ let shell = port.ask();+ next = Instant::now() + every;+ gone_since = if shell.says_gone() {+ gone_since.or(Some(asked))+ } else {+ None+ };+ if !matches!(shell, Shell::Answered { held: true, .. }) {+ // An icon added again (Explorer started again) has the first tip.+ set = None;+ }+ let changed = last != Some(shell);+ last = Some(shell);+ {+ let mut s = worker.lock();+ if s.closed {+ return;+ }+ s.seen = Some(Seen {+ shell,+ asked,+ gone_since,+ });+ }+ if changed {+ log(shell);+ wake();+ }+ }+ let (tip, number) = {+ let s = worker.lock();+ if s.closed {+ return;+ }+ (s.tip.clone(), s.tip_number)+ };+ let held = matches!(last, Some(Shell::Answered { held: true, .. }));+ if let Some(tip) = tip+ && held+ && set != Some(number)+ && port.tip(&tip)+ {+ set = Some(number);+ }+ // Until the next question, or a new tip (one the shell didn't take is tried+ // again with the next question).+ let mut s = worker.lock();+ while !s.closed && s.tip_number == number {+ let left = next.saturating_duration_since(Instant::now());+ if left.is_zero() {+ break;+ }+ s = worker+ .told+ .wait_timeout(s, left)+ .unwrap_or_else(PoisonError::into_inner)+ .0;+ }+ if s.closed {+ return;+ }+ }+ });+ if let Err(e) = spawned {+ tracing::warn!("tray icon: no thread to ask the shell ({e}): its answer stays unknown");+ }+ Watch { shared }+ }++ /// The last answer; None before the first, or while the watcher is writing one. Never waits.+ pub fn latest(&self) -> Option<Seen> {+ self.shared.try_lock().and_then(|s| s.seen)+ }++ /// Have the icon's tip set to `tip`. False if the watcher was busy writing an answer: asked+ /// again at the next frame. Never waits.+ pub fn tip(&self, tip: &str) -> bool {+ let Some(mut s) = self.shared.try_lock() else {+ return false;+ };+ if s.tip.as_deref() != Some(tip) {+ s.tip = Some(tip.to_owned());+ s.tip_number += 1;+ self.shared.told.notify_one();+ }+ true+ }+}++impl Drop for Watch {+ fn drop(&mut self) {+ // Never joined: the thread may be inside a question the shell never answers.+ self.shared.lock().closed = true;+ self.shared.told.notify_one();+ }+}++/// The shell's answer in the log, when it changes: a log in a report says which case it was.+fn log(shell: Shell) {+ match shell {+ Shell::NoTaskbar => tracing::info!("tray icon: no taskbar (Explorer isn't running)"),+ Shell::Silent => tracing::info!("tray icon: the shell didn't answer"),+ Shell::Answered { placed, held } => {+ tracing::info!("tray icon: placed {placed}, held by the shell {held}")+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::mpsc;++ fn seen(shell: Shell, asked: Instant) -> Option<Seen> {+ Some(Seen {+ shell,+ asked,+ gone_since: shell.says_gone().then_some(asked),+ })+ }++ const HELD: Shell = Shell::Answered {+ placed: false,+ held: true,+ };+ const PLACED: Shell = Shell::Answered {+ placed: true,+ held: false,+ };+ const NONE: Shell = Shell::Answered {+ placed: false,+ held: false,+ };++ /// An icon the shell holds (behind ^, maybe with no place: #750, #718, #754) or places is+ /// there; a running shell that has neither, or no taskbar, says it is gone.+ #[test]+ fn held_or_placed_is_there_and_only_the_shell_says_gone() {+ let now = Instant::now();+ for shell in [+ HELD,+ PLACED,+ Shell::Answered {+ placed: true,+ held: true,+ },+ ] {+ assert_eq!(icon(seen(shell, now), now), Icon::There, "{shell:?}");+ }+ assert_eq!(icon(seen(NONE, now), now), Icon::Gone);+ assert_eq!(icon(seen(Shell::NoTaskbar, now), now), Icon::Gone);+ }++ /// No answer yet, a shell that didn't answer, an answer too old (or a lock the watcher holds:+ /// `latest` gives None, as before the first) is unknown, never gone.+ #[test]+ fn no_answer_or_an_old_one_is_unknown() {+ let now = Instant::now();+ assert_eq!(icon(None, now), Icon::Unknown);+ assert_eq!(icon(seen(Shell::Silent, now), now), Icon::Unknown);+ for shell in [HELD, NONE, Shell::NoTaskbar] {+ let old = now.checked_sub(STALE).unwrap();+ assert_eq!(icon(seen(shell, old), now), Icon::Unknown, "{shell:?}");+ let recent = now.checked_sub(STALE - Duration::from_millis(1)).unwrap();+ assert_ne!(icon(seen(shell, recent), now), Icon::Unknown, "{shell:?}");+ }+ }++ /// A hidden window comes back only once a running shell has said for RESCUE_AFTER, answer+ /// after answer, that it has no icon: not on no answer, an old or a silent one, a short gap+ /// (Explorer starting again), or while there is no taskbar at all.+ #[test]+ fn only_a_lasting_answer_of_no_icon_brings_a_hidden_window_back() {+ let now = Instant::now();+ let long_ago = now.checked_sub(RESCUE_AFTER).unwrap();+ let gone = |shell, since| {+ Some(Seen {+ shell,+ asked: now,+ gone_since: Some(since),+ })+ };+ assert!(rescue(gone(NONE, long_ago), now));+ assert!(!rescue(gone(NONE, now - Duration::from_secs(3)), now));+ assert!(!rescue(gone(Shell::NoTaskbar, long_ago), now));+ assert!(!rescue(None, now));+ assert!(!rescue(seen(Shell::Silent, now), now));+ assert!(!rescue(seen(HELD, now), now));+ // The last of a long run of "no icon", but from long ago: the shell stopped answering.+ let stale = Some(Seen {+ shell: NONE,+ asked: now.checked_sub(STALE).unwrap(),+ gone_since: Some(long_ago.checked_sub(STALE).unwrap()),+ });+ assert!(!rescue(stale, now));+ }++ /// A fake shell: answers what the test sends, waiting for it (for ever, if nothing comes).+ struct Fake {+ answers: mpsc::Receiver<Shell>,+ asked: mpsc::Sender<()>,+ tips: mpsc::Sender<String>,+ take_tips: bool,+ }++ impl Port for Fake {+ fn ask(&mut self) -> Shell {+ let _ = self.asked.send(());+ self.answers.recv().unwrap_or(Shell::Silent)+ }+ fn tip(&mut self, tip: &str) -> bool {+ let _ = self.tips.send(tip.to_owned());+ self.take_tips+ }+ }++ /// Have the tip set, as the window does at each frame until the watch isn't busy.+ fn tip(w: &Watch, tip: &str) {+ while !w.tip(tip) {+ std::thread::yield_now();+ }+ }++ /// How often the tests' watches ask: the fake shell answers when the test says.+ const QUICK: Duration = Duration::from_millis(20);++ fn fake(+ take_tips: bool,+ ) -> (+ Fake,+ mpsc::Sender<Shell>,+ mpsc::Receiver<()>,+ mpsc::Receiver<String>,+ ) {+ let (answer, answers) = mpsc::channel();+ let (asked, was_asked) = mpsc::channel();+ let (tips, tipped) = mpsc::channel();+ (+ Fake {+ answers,+ asked,+ tips,+ take_tips,+ },+ answer,+ was_asked,+ tipped,+ )+ }++ /// #747: a shell that never answers holds up nothing: the window's reads and tips return at+ /// once, the answer stays unknown, and dropping the watch doesn't wait for the thread.+ #[test]+ fn a_shell_that_never_answers_holds_up_nothing() {+ let (port, _answer, was_asked, _tipped) = fake(true);+ let w = Watch::every(QUICK, port, || {});+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ let start = Instant::now();+ for _ in 0..10_000 {+ assert_eq!(w.latest(), None);+ assert!(w.tip("MDM"));+ assert_eq!(icon(w.latest(), Instant::now()), Icon::Unknown);+ }+ drop(w);+ assert!(start.elapsed() < Duration::from_secs(2));+ }++ /// The window reading while the watcher writes gets None, unknown: never gone.+ #[test]+ fn a_busy_watch_is_no_answer() {+ let (port, answer, was_asked, _tipped) = fake(true);+ let w = Watch::every(QUICK, port, || {});+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(NONE).unwrap();+ let start = Instant::now();+ while w.latest().is_none() {+ assert!(start.elapsed() < Duration::from_secs(5));+ std::thread::yield_now();+ }+ let _writing = w.shared.lock();+ assert_eq!(w.latest(), None);+ assert_eq!(icon(w.latest(), Instant::now()), Icon::Unknown);+ assert!(+ !w.tip("MDM"),+ "a busy watch takes the tip at the next frame"+ );+ }++ /// Answers reach the window, which is woken only when one differs from the one before; the+ /// tip is set once the shell holds the icon, and again once the icon comes back.+ #[test]+ fn answers_wake_the_window_when_they_change_and_the_tip_follows_the_icon() {+ let (port, answer, was_asked, tipped) = fake(true);+ let (woke, woken) = mpsc::channel();+ let w = Watch::every(QUICK, port, move || {+ let _ = woke.send(());+ });+ tip(&w, "MDM 1");+ // Not held yet: no tip set.+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(NONE).unwrap();+ woken.recv_timeout(Duration::from_secs(5)).unwrap();+ assert_eq!(w.shared.lock().seen.map(|s| s.shell), Some(NONE));+ assert!(tipped.recv_timeout(Duration::from_millis(200)).is_err());+ // Held: the tip goes, and the window is woken.+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(HELD).unwrap();+ woken.recv_timeout(Duration::from_secs(5)).unwrap();+ assert_eq!(+ tipped.recv_timeout(Duration::from_secs(5)).unwrap(),+ "MDM 1"+ );+ // The same answer again: no wake, and the tip isn't sent again.+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(HELD).unwrap();+ assert!(woken.recv_timeout(Duration::from_millis(300)).is_err());+ assert!(tipped.try_recv().is_err());+ // A new tip goes with the next answer.+ tip(&w, "MDM 2");+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(HELD).unwrap();+ assert_eq!(+ tipped.recv_timeout(Duration::from_secs(5)).unwrap(),+ "MDM 2"+ );+ // The icon lost and added back (Explorer started again): the tip is set again.+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(Shell::NoTaskbar).unwrap();+ woken.recv_timeout(Duration::from_secs(5)).unwrap();+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(HELD).unwrap();+ assert_eq!(+ tipped.recv_timeout(Duration::from_secs(5)).unwrap(),+ "MDM 2"+ );+ }++ /// "Gone" is dated from the first of an unbroken run of such answers: one answer that isn't+ /// (the icon back, or no answer) starts it again.+ #[test]+ fn the_run_of_gone_answers_restarts_after_any_other() {+ let (port, answer, was_asked, _tipped) = fake(false);+ let w = Watch::every(QUICK, port, || {});+ let next = |shell| {+ was_asked.recv_timeout(Duration::from_secs(5)).unwrap();+ answer.send(shell).unwrap();+ let start = Instant::now();+ loop {+ if let Some(s) = w.latest()+ && s.shell == shell+ {+ return s;+ }+ assert!(start.elapsed() < Duration::from_secs(5));+ std::thread::yield_now();+ }+ };+ let first = next(NONE);+ assert_eq!(first.gone_since, Some(first.asked));+ let second = next(Shell::NoTaskbar);+ assert_eq!(second.gone_since, Some(first.asked));+ let silent = next(Shell::Silent);+ assert_eq!(silent.gone_since, None);+ let again = next(NONE);+ assert_eq!(again.gone_since, Some(again.asked));+ }+}diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rsindex 9c27b9e3..c4f15d66 100644--- a/crates/app/src/win32.rs+++ b/crates/app/src/win32.rs@@ -1851,40 +1851,133 @@ 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+/// The highest icon id [`tray_icon_ask`] 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() }+/// Longer than the shell takes to answer about an icon: a "no" that took this long is+/// Shell_NotifyIcon giving up on a busy Explorer, not the shell's answer.+const TRAY_SLOW: std::time::Duration = std::time::Duration::from_millis(1500);++/// What the shell said of MDM's notification-area icon ([`tray_icon_ask`]).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TrayAnswer {+ /// No taskbar (no `Shell_TrayWnd` window): Explorer isn't running, or a shell without a+ /// notification area is.+ NoTaskbar,+ /// The taskbar is there but didn't answer: Windows says it stopped responding, or the+ /// question took as long as a timeout.+ Silent,+ /// The shell answered: the icon's id when it holds it (wherever it shows it), and whether it+ /// gives the icon a place on screen.+ Answered { held: Option<u32>, placed: bool },+}++/// Ask the shell about the notification-area icon of `hwnd` (the tray's own hidden window, which+/// has one icon); `known` is its id once found. Both questions wait for Explorer, for seconds when+/// it is busy (#747: 8 s), so this runs on the tray's watcher thread (tray.rs), never on the+/// window's.+///+/// - Held: an empty `NIM_MODIFY` changes nothing and succeeds only for an icon the shell has, in+/// the taskbar or among the hidden icons behind ^ (`known` first, else each id up to+/// [`TRAY_ICON_IDS`]).+/// - Placed: `Shell_NotifyIconGetRect`. Not enough on its own: Windows 10 and Windows 11 builds+/// before 26200 give an icon behind ^ no place (#750, #718, #754: 0.5.2 asked only this, and+/// left the window in the taskbar with the icon there); build 26200 gives it the place of ^.+///+/// `rect_withheld` answers "no place" without asking (MDM_TEST_TRAY_RECT=0: the reporters' case,+/// on a Windows that gives one).+pub fn tray_icon_ask(hwnd: isize, known: Option<u32>, rect_withheld: bool) -> TrayAnswer {+ use windows_sys::Win32::UI::WindowsAndMessaging::{FindWindowW, IsHungAppWindow};+ let hwnd = hwnd as HWND;+ if hwnd.is_null() {+ return TrayAnswer::Answered {+ held: None,+ placed: false,};- // SAFETY: nid lives for the call; the shell only reads it.- unsafe { Shell_NotifyIconW(NIM_MODIFY, &nid) != 0 }+ }+ let class: Vec<u16> = "Shell_TrayWnd\0".encode_utf16().collect();+ // SAFETY: a NUL-ended class name and no title: no window is sent a message.+ let taskbar = unsafe { FindWindowW(class.as_ptr(), std::ptr::null()) };+ if taskbar.is_null() {+ return TrayAnswer::NoTaskbar;+ }+ // SAFETY: reads the window's state; never waits for it.+ if unsafe { IsHungAppWindow(taskbar) } != 0 {+ return TrayAnswer::Silent;+ }+ let start = std::time::Instant::now();+ let ids = || {+ known+ .into_iter()+ .chain((1..=TRAY_ICON_IDS).filter(move |id| Some(*id) != known))};- if hwnd.is_null() {- return None;+ let held = ids().find(|id| tray_icon_held(hwnd, *id));+ // An icon it doesn't hold is asked for its place too, under each id: should an empty+ // NIM_MODIFY fail on some Windows for an icon it has, its place still says it is there.+ let placed = !rect_withheld+ && match held {+ Some(id) => tray_icon_placed(hwnd, id),+ None => ids().any(|id| tray_icon_placed(hwnd, id)),+ };+ if held.is_none() && !placed && start.elapsed() >= TRAY_SLOW {+ return TrayAnswer::Silent;}- known- .into_iter()- .chain(1..=TRAY_ICON_IDS)- .find(|id| held(*id))+ TrayAnswer::Answered { held, placed }+}++/// Whether the shell holds icon `id` of `hwnd`: an empty `NIM_MODIFY`.+fn tray_icon_held(hwnd: HWND, id: u32) -> bool {+ use windows_sys::Win32::UI::Shell::{NIM_MODIFY, NOTIFYICONDATAW, Shell_NotifyIconW};+ 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 }+}++/// Whether the shell gives icon `id` of `hwnd` a place on screen.+fn tray_icon_placed(hwnd: HWND, id: u32) -> bool {+ use windows_sys::Win32::UI::Shell::{NOTIFYICONIDENTIFIER, Shell_NotifyIconGetRect};+ let ident = NOTIFYICONIDENTIFIER {+ cbSize: size_of::<NOTIFYICONIDENTIFIER>() as u32,+ hWnd: hwnd,+ uID: id,+ // SAFETY: a plain C struct; with a zero GUID the icon is named by its window and id.+ ..unsafe { zeroed() }+ };+ // SAFETY: a plain C struct, written by the call.+ let mut rect: RECT = unsafe { zeroed() };+ // SAFETY: both live for the call.+ unsafe { Shell_NotifyIconGetRect(&ident, &mut rect) >= 0 }+}++/// Set the tip of icon `id` of `hwnd` (127 characters at most, the rest cut). Waits for Explorer+/// as [`tray_icon_ask`] does, so it too runs on the tray's watcher thread. False when the shell+/// didn't take it (no such icon, or no answer).+pub fn tray_icon_tip(hwnd: isize, id: u32, tip: &str) -> bool {+ use windows_sys::Win32::UI::Shell::{NIF_TIP, NIM_MODIFY, NOTIFYICONDATAW, Shell_NotifyIconW};+ let mut nid = NOTIFYICONDATAW {+ cbSize: size_of::<NOTIFYICONDATAW>() as u32,+ hWnd: hwnd as HWND,+ uID: id,+ uFlags: NIF_TIP,+ // SAFETY: a plain C struct; all zero is its empty value.+ ..unsafe { zeroed() }+ };+ // The last unit stays the NUL that ends it.+ let room = nid.szTip.len() - 1;+ for (slot, unit) in nid.szTip.iter_mut().zip(tip.encode_utf16().take(room)) {+ *slot = unit;+ }+ // SAFETY: nid lives for the call; the shell only reads it.+ unsafe { Shell_NotifyIconW(NIM_MODIFY, &nid) != 0 }}/// What a borderless window of ours is, for [`popup_window`]: every one is a plain popupdiff --git a/crates/app/tests/close_without_tray.rs b/crates/app/tests/close_without_tray.rsindex 2abaca6a..12ad8607 100644--- a/crates/app/tests/close_without_tray.rs+++ b/crates/app/tests/close_without_tray.rs@@ -121,6 +121,20 @@ fn data(dir: &Path, name: &str, close_to_tray: bool) -> PathBuf {/// Post WM_CLOSE to the app's main window. True when one was found.fn close_main(pid: u32) -> bool {+ main_window(+ pid,+ "[CW]::PostMessage($h, 0x10, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null",+ ) == "True"+}++/// Whether the app's main window is visible ("True" or "False"; "" when there is none).+fn main_visible(pid: u32) -> String {+ main_window(pid, "$script:visible = [CW]::IsWindowVisible($h)")+}++/// Run `action` on the app's main window (`$h`); "True" when one was found, or what the action+/// put in `$script:visible`.+fn main_window(pid: u32, action: &str) -> String {let script = r#"Add-Type @'using System;@@ -132,9 +146,11 @@ public static class CW {[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint p);[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);}'@$script:closed = $false+$script:visible = $null[CW]::EnumWindows({param($h, $l)$p = 0@@ -143,21 +159,39 @@ $script:closed = $false$t = New-Object System.Text.StringBuilder 512[CW]::GetWindowText($h, $t, 512) | Out-Nullif ($t.ToString() -eq 'TITLE') {- [CW]::PostMessage($h, 0x10, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null+ ACTION$script:closed = $true}}$true}, [IntPtr]::Zero) | Out-Null-$script:closed+if ($script:visible -ne $null) { $script:visible } elseif ($script:closed) { $script:closed } else { '' }"#.replace("PID", &pid.to_string())- .replace("TITLE", MAIN);+ .replace("TITLE", MAIN)+ .replace("ACTION", action);let out = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &script]).output().unwrap();- String::from_utf8_lossy(&out.stdout).trim() == "True"+ String::from_utf8_lossy(&out.stdout).trim().to_owned()+}++/// Wait until the app's main window is visible or not, failing after `wait`.+fn wait_visible(pid: u32, visible: bool, wait: Duration) {+ let until = Instant::now() + wait;+ let want = if visible { "True" } else { "False" };+ loop {+ let now = main_visible(pid);+ if now == want {+ return;+ }+ assert!(+ Instant::now() < until,+ "the main window's visibility is '{now}', not {want}"+ );+ std::thread::sleep(Duration::from_millis(300));+ }}#[test]@@ -229,7 +263,7 @@ fn closing_follows_the_option_and_the_tray_icon() {/// 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).+/// behind ^ (#750, #718, #754, #545).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")@@ -238,8 +272,9 @@ fn env_real<'a>(cmd: &'a mut Command, data: &Path, placed: bool) -> &'a mut Comm}/// 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.+/// the icon is (a new icon goes behind ^, where the shell may give it none), and a second start+/// brings the window back. The shell is this machine's, asked by the app's tray thread (#747):+/// 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() {@@ -254,24 +289,27 @@ fn closing_hides_to_an_icon_the_shell_holds() {);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",+ &format!("tray icon: placed {placed}, held by the shell true"),Duration::from_secs(10),);- let text = log(&data);- assert!(- text.contains(&format!(- "tray icon: placed {placed}, held by the shell true"- )),- "{text}"+ assert!(close_main(app.id()), "no main window to close");+ wait_for(+ &mut app,+ &data,+ "close: hidden to the notification area (tray icon: There)",+ Duration::from_secs(10),);+ wait_visible(app.id(), false, Duration::from_secs(10));assert!(app.try_wait().unwrap().is_none(),"the app quit instead of hiding");+ // A second start brings the hidden window back, icon or not.+ let _ = env_real(&mut Command::new(APP), &data, placed).status();+ wait_visible(app.id(), true, Duration::from_secs(10));let _ = env_real(&mut Command::new(APP), &data, placed).arg("/exit").status();diff --git a/crates/app/tests/startup_tray.rs b/crates/app/tests/startup_tray.rsindex 90206679..5763d990 100644--- a/crates/app/tests/startup_tray.rs+++ b/crates/app/tests/startup_tray.rs@@ -55,7 +55,7 @@ fn env<'a>(cmd: &'a mut Command, data: &Path, startup: &Startup) -> &'a mut Commcmd.env("MDM_DATA_DIR", data).env("MDM_OFFSCREEN", "1").env("MDM_TEST_TRAY", "1")- // A test's shell isn't asked where the icon is: say it is shown (app.rs tray_shown).+ // A test's shell isn't asked where the icon is: say it is shown (app.rs tray_icon)..env("MDM_TEST_TRAY_VISIBLE", "1");#[cfg(windows)]cmd.env("MDM_TEST_RUN_VALUE", &startup.name);