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: the title bar's light or dark set once, not checked with DWM every 2 s (#633, #583) (#641)
Ahmed Nefzaoui5213ad1f036f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dda525cb..9f00aeb2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -46,6 +46,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see- 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)).- 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)).- Windows: MDM no longer crashes ("crash in ntdll.dll", the heap corrupted) when the clipboard is read in two places at once, as when **Add URL** opened while the clipboard monitor was looking for a copied link. Windows lets the parts of one program open the clipboard together, and their reads spoiled each other's data; MDM's reads and writes of the clipboard, a paste or copy in a text box included, now go one at a time ([#629](https://github.com/anefzaoui/misterdownloadmanager/issues/629)).- macOS: downloads to a network volume (a folder under `/Volumes` on an SMB, AFP or NFS share) start again. Each one was refused with "Not enough disk space ... 0 bytes free", however much the share had: macOS answers 0 when asked a network volume's space "for important usage" (the free space plus what the system can clear, as Finder counts it on the Mac's own disks), and MDM took that 0. On a network volume, or whenever that answer is 0, MDM now counts the free space the volume reports ([#623](https://github.com/anefzaoui/misterdownloadmanager/issues/623)).### Addeddiff --git a/ROADMAP.md b/ROADMAP.mdindex d46b22f8..58308c85 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -561,6 +561,10 @@ These ship in a later version, when they're ready.### Bugs being looked into+- π Windows: the window stopping on a stalled system while it checked its title bar's colours+ ([#633](https://github.com/anefzaoui/misterdownloadmanager/issues/633),+ [#583](https://github.com/anefzaoui/misterdownloadmanager/issues/583)): the colours are now set+ once, when a window opens or the theme changes; fix in review- π Downloads from FileHippo failing at once with 412 Precondition Failed([#630](https://github.com/anefzaoui/misterdownloadmanager/issues/630)): a link the site refusesto MDM now goes on from where the browser's own download of it had reached; fix in review, stilldiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex ed12b610..4bf0d865 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -8961,12 +8961,10 @@ impl App {} else {changed};- // The caption follows (first check: the window may not exist yet; retried).+ // The caption follows (first check: the window may not exist yet; retried). Only+ // then: asking DWM every 2 s caught the window's thread in a stalled system (#633).if changed || !self.caption_set {crate::theme::apply_mode(&ctx);- }- // Re-asserted on every check (a no-op when already right).- {#[cfg(windows)]{self.caption_set =diff --git a/crates/app/src/crashui.rs b/crates/app/src/crashui.rsindex defe82b6..f9d4619f 100644--- a/crates/app/src/crashui.rs+++ b/crates/app/src/crashui.rs@@ -191,6 +191,10 @@ struct ReportWindow {icon: Option<egui::TextureHandle>,/// Windows' caption follows the window's theme (set once the window exists).caption_set: bool,+ /// DWM gave the caption its light or dark (once: asked every second, it caught the window's+ /// thread in a stalled system, #633).+ #[cfg(windows)]+ caption_dwm: bool,/// Brought inside the screen once it exists (scale::fit_window, #262).fitted: bool,}@@ -209,6 +213,8 @@ impl ReportWindow {told: None,icon: None,caption_set: false,+ #[cfg(windows)]+ caption_dwm: false,fitted: false,}}@@ -326,12 +332,14 @@ impl eframe::App for ReportWindow {let layout = egui::vec2(CLIENT[0], CLIENT[1]);crate::scale::fit_window(ui.ctx(), egui::vec2(120.0, 120.0), Some(layout));}- // Re-asserted as the main window does (winit can set it back from Windows' own mode).+ // And through DWM, as the main window's, once the window is there.#[cfg(windows)]- crate::win32::caption_dark(- crate::i18n::t("Mister Download Manager crash report"),- crate::theme::dark_surface(),- );+ if !self.caption_dwm {+ self.caption_dwm = crate::win32::caption_dark(+ crate::i18n::t("Mister Download Manager crash report"),+ crate::theme::dark_surface(),+ );+ }while let Ok(e) = self.events.try_recv() {if matches!(e, Event::Recovered) {self.recovered = true;diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rsindex bcd67224..29cb24ae 100644--- a/crates/app/src/dialogs.rs+++ b/crates/app/src/dialogs.rs@@ -125,6 +125,7 @@ pub fn keep_theme(let theme_key = key.with("theme");let shown_key = key.with("shown");let front_key = key.with("front");+ let caption_key = key.with("caption");// Not drawn in the last pass, the window is gone and this is a new one, hidden until it is// told otherwise, whatever the last one was told (#440).if !open || window_was_gone(ctx, key.with("theme-pass")) {@@ -132,6 +133,7 @@ pub fn keep_theme(d.remove::<bool>(theme_key);d.remove::<bool>(shown_key);d.remove::<u32>(front_key);+ d.remove::<bool>(caption_key);});}if !open {@@ -182,11 +184,17 @@ pub fn keep_theme(}#[cfg(not(windows))]let _ = front_key;- // Belt and braces: a no-op when the caption is already right.+ // Belt and braces, once per window and theme (until the window is found): asked every frame,+ // the window's thread waited on DWM, or on a busy window of this process while looking for+ // its own, in a stalled system (#633, #583).#[cfg(windows)]- crate::win32::caption_dark(title, dark);+ if ctx.data(|d| d.get_temp::<bool>(caption_key)) != Some(dark)+ && crate::win32::caption_dark(title, dark)+ {+ ctx.data_mut(|d| d.insert_temp(caption_key, dark));+ }#[cfg(not(windows))]- let _ = title;+ let _ = (title, caption_key);}/// Whether the window `key` is drawn again after a pass that didn't draw it: egui destroys adiff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rsindex f113a92c..cbf1b37d 100644--- a/crates/app/src/theme.rs+++ b/crates/app/src/theme.rs@@ -185,9 +185,8 @@ pub fn apply_mode(ctx: &egui::Context) {egui::epaint::FontColorTransferFunction::LIGHT_MODE_DEFAULT};ctx.all_styles_mut(|s| s.visuals.text_options.color_transfer_function = tf);- // eframe applies egui's theme preference to every window's caption; keep it in step so it- // doesn't reset the captions to the system theme. egui's dark or light style is the mode's- // variant (`apply_theme` puts each variant into its egui theme).+ // egui's dark or light style is the mode's variant (`apply_theme` puts each variant into its+ // egui theme). It leaves the windows' captions alone (`apply`: `sync_window_theme`).ctx.set_theme(if dark() {egui::ThemePreference::Dark} else {@@ -963,6 +962,11 @@ pub fn apply(ctx: &egui::Context) {// Ctrl + / Ctrl β / Ctrl 0 step through View β Interface size and are saved (scale.rs),// not egui's own 10 % steps.o.zoom_with_keyboard = false;+ // Every window's theme (its caption) is MDM's to give: the main window's in+ // `apply_mode`, each dialog's in `dialogs::keep_theme`, the caption the theme's surface.+ // egui's own would set the mode's instead, behind them, and the caption would have to+ // be checked with DWM again and again (#633).+ o.sync_window_theme = false;});egui_extras::install_image_loaders(ctx);apply_theme(ctx);diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rsindex 96d47d2c..356be333 100644--- a/crates/app/src/win32.rs+++ b/crates/app/src/win32.rs@@ -17,7 +17,7 @@ use windows_sys::Win32::UI::Shell::{};use windows_sys::Win32::UI::WindowsAndMessaging::{DestroyIcon, EnumWindows, GWL_EXSTYLE, GWL_STYLE, GetIconInfo, GetWindowLongPtrW,- GetWindowTextW, GetWindowThreadProcessId, ICONINFO, NCCALCSIZE_PARAMS, SWP_FRAMECHANGED,+ GetWindowThreadProcessId, ICONINFO, InternalGetWindowText, NCCALCSIZE_PARAMS, SWP_FRAMECHANGED,SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SetWindowLongPtrW, SetWindowPos, WM_NCCALCSIZE,WM_NCHITTEST, WS_EX_DLGMODALFRAME, WS_THICKFRAME,};@@ -40,8 +40,11 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> windows_sys::coif pid != f.pid {return 1;}- // SAFETY: GetWindowTextW writes at most buf.len() units, the NUL included.- let n = unsafe { GetWindowTextW(hwnd, f.buf.as_mut_ptr(), f.buf.len() as i32) };+ // The title as the window keeps it, read without a message: GetWindowTextW sends WM_GETTEXT+ // to a window of this process, and one whose thread is busy (on a stalled disk: the file+ // icons' COM window) held the window's thread until it answered (#583).+ // SAFETY: InternalGetWindowText writes at most buf.len() units, the NUL included.+ let n = unsafe { InternalGetWindowText(hwnd, f.buf.as_mut_ptr(), f.buf.len() as i32) };if n > 0 && f.buf[..n as usize] == f.title[..] {f.found = hwnd;return 0;@@ -1543,6 +1546,90 @@ mod find_own_window_tests {}}}++ /// A hidden test window of this thread titled `title`, destroyed by the caller.+ fn test_window(title: &str) -> HWND {+ let class: Vec<u16> = "mdm-find-own-window-test-2\0".encode_utf16().collect();+ let t: Vec<u16> = title.encode_utf16().chain(Some(0)).collect();+ // SAFETY: a class registered with the system's own procedure (again: a no-op), and a+ // hidden window of it on this thread; the strings are NUL-terminated.+ unsafe {+ let mut wc: WNDCLASSW = zeroed();+ wc.lpfnWndProc = Some(DefWindowProcW);+ wc.lpszClassName = class.as_ptr();+ RegisterClassW(&wc);+ let h = CreateWindowExW(+ 0,+ class.as_ptr(),+ t.as_ptr(),+ 0,+ -20000,+ -20000,+ 100,+ 100,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null(),+ );+ assert!(!h.is_null());+ h+ }+ }++ /// #583: looking for our window doesn't wait for another thread of this process whose window+ /// isn't answering (busy, on a stalled disk): the titles are read without a message.+ #[test]+ fn a_busy_threads_window_does_not_hold_the_search() {+ let pid = std::process::id();+ let (made, window_made) = std::sync::mpsc::channel();+ let (release, released) = std::sync::mpsc::channel::<()>();+ let busy = std::thread::spawn(move || {+ let h = test_window(&format!("mdm busy window {pid}"));+ made.send(()).unwrap();+ // Busy: no message is taken until the test is done.+ let _ = released.recv();+ // SAFETY: the window made above, on this thread.+ unsafe { DestroyWindow(h) };+ });+ window_made.recv().unwrap();+ let (answer, answered) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let _ = answer.send(find_own_window(&format!("mdm no such window {pid}")).is_some());+ });+ let got = answered.recv_timeout(std::time::Duration::from_secs(3));+ release.send(()).unwrap();+ busy.join().unwrap();+ assert_eq!(+ got,+ Ok(false),+ "the search waited for the busy thread's window"+ );+ }++ /// #633: DWM is asked for a window's caption once per change, not each time it's re-asserted.+ #[test]+ fn the_caption_goes_to_dwm_only_when_it_changes() {+ use std::sync::atomic::Ordering::Relaxed;+ let title = format!("mdm caption test {}", std::process::id());+ let h = test_window(&title);+ let calls = || CAPTION_DWM_CALLS.load(Relaxed);+ let before = calls();+ for _ in 0..50 {+ assert!(caption_dark(&title, true));+ }+ assert_eq!(calls() - before, 1, "dark, asked once");+ for _ in 0..50 {+ assert!(caption_dark(&title, false));+ }+ assert_eq!(calls() - before, 2, "light, once more");+ assert!(caption_dark(&title, true));+ assert_eq!(calls() - before, 3, "dark again");+ // SAFETY: the window made above, on this thread.+ unsafe { DestroyWindow(h) };+ assert!(!caption_dark(&title, true), "gone: not found");+ assert_eq!(calls() - before, 3);+ }}#[cfg(test)]@@ -2157,27 +2244,53 @@ pub fn menu_text_width(text: &str) -> i32 {w}+thread_local! {+ /// The caption each of our windows was last given by [`caption_dark`] (dark: true).+ static CAPTION_DARK: std::cell::RefCell<std::collections::HashMap<isize, bool>> =+ Default::default();+}++/// Whether DWM is to be told `dark` for window `hwnd`: not when that is what it was last told.+/// Windows that are gone are forgotten.+fn caption_news(hwnd: isize, dark: bool, alive: impl Fn(isize) -> bool) -> bool {+ CAPTION_DARK.with(|m| {+ let Ok(mut m) = m.try_borrow_mut() else {+ return true;+ };+ if m.get(&hwnd) == Some(&dark) {+ return false;+ }+ m.retain(|h, _| alive(*h));+ m.insert(hwnd, dark);+ true+ })+}++/// How many times [`caption_dark`] has asked DWM, for the tests.+#[cfg(test)]+static CAPTION_DWM_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+/// Give our window titled `title` a dark or light caption (DWM). Returns false if not found.+/// DWM is asked only when the window's caption changes, never again for the same one: a call+/// into DWM waits on a system that is stalled (its disk, its memory), and the window's thread+/// waited with it, every 2 s (#633). Callers call it when the theme changes and for a new window.pub fn caption_dark(title: &str, dark: bool) -> bool {use windows_sys::Win32::Graphics::Dwm::{DWMWA_USE_IMMERSIVE_DARK_MODE, DwmSetWindowAttribute};+ use windows_sys::Win32::Graphics::Gdi::{RDW_FRAME, RDW_INVALIDATE, RedrawWindow};+ use windows_sys::Win32::UI::WindowsAndMessaging::IsWindow;let Some(hwnd) = find_own_window(title) else {return false;};- use windows_sys::Win32::Graphics::Dwm::DwmGetWindowAttribute;- use windows_sys::Win32::Graphics::Gdi::{RDW_FRAME, RDW_INVALIDATE, RedrawWindow};+ // SAFETY: a plain query; any value is accepted as the handle.+ let alive = |h: isize| unsafe { IsWindow(h as HWND) } != 0;+ if !caption_news(hwnd as isize, dark, alive) {+ return true;+ }+ #[cfg(test)]+ CAPTION_DWM_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);let v: i32 = dark.into();// SAFETY: documented attribute with a 4-byte BOOL value.unsafe {- let mut cur: i32 = -1;- DwmGetWindowAttribute(- hwnd,- DWMWA_USE_IMMERSIVE_DARK_MODE as u32,- &mut cur as *mut i32 as *mut c_void,- size_of::<i32>() as u32,- );- if cur == v {- return true;- }DwmSetWindowAttribute(hwnd,DWMWA_USE_IMMERSIVE_DARK_MODE as u32,