Skip to content

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

A minimized MDM keeps working: queues, Scheduler, limits, kill switch, saving (after #173) (#176)

Ahmed Nefzaoui7313abb16768
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cac90b08..c3b794b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -344,6 +344,11 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **A minimized MDM keeps working**: with the main window minimized (not to the notification
+ area), queues didn't start their next file, the Scheduler's starts and stops didn't fire,
+ download limits, the network adapter's kill switch, the clipboard monitor, the update check, the
+ taskbar's progress and saving the list all waited until the window was restored. They run in
+ every window state now, and their windows (Download complete, a limit's notice) open at once.
- **HLS and DASH videos from the browser, as their stream**
([#155](https://github.com/anefzaoui/misterdownloadmanager/issues/155)): a video played as a
stream (most sites' long videos) failed with yt-dlp's "Unsupported URL" when the extension sent
diff --git a/ROADMAP.md b/ROADMAP.md
index b64854fb..f4f0dcc2 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -13,6 +13,8 @@ Everything below ships together, in one release.
### Done
+- ✅ A minimized MDM keeps working: queues, the Scheduler, download limits, the kill switch and
+ saving the list no longer wait for the window to be restored
- ✅ HLS and DASH videos from the browser reach yt-dlp as their stream, by the button over the
video, the right-click menu (it did nothing in Firefox) and the media list
([#155](https://github.com/anefzaoui/misterdownloadmanager/issues/155))
@@ -165,8 +167,6 @@ Everything below ships together, in one release.
contrast; then style themes with their own control shapes, a drawn title bar on Windows and their
own icons: Metro first, then Adwaita and Breeze, then Luna, Aero and Aqua with icons drawn for
MDM. Theme files can be added by anyone, and Base16 and pywal schemes imported
-- 🔄 A minimized MDM keeps working: queues, the Scheduler, speed limits, the kill switch and saving
- no longer wait for the window to be restored (after [#162](https://github.com/anefzaoui/misterdownloadmanager/issues/162))
- 🔄 Where a download's server is: its country, flag and round trip, from a table that comes with
MDM; no address is sent anywhere ([#140](https://github.com/anefzaoui/misterdownloadmanager/issues/140))
- 🔄 Torrents: download in order, to watch a video while it downloads; the other torrents rarest
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 84708458..621c37e9 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -475,6 +475,8 @@ pub struct App {
saver: store::Saver,
/// When the light/dark mode was last checked against Windows' app mode.
theme_checked: Option<Instant>,
+ /// When `logic`'s every-2-seconds work last ran (crash state, torrents, #174).
+ ticked: Option<Instant>,
/// The main window's caption matches the mode.
caption_set: bool,
list: list::ListState,
@@ -879,6 +881,7 @@ impl App {
last_save: Instant::now(),
saver: store::Saver::new(),
theme_checked: None,
+ ticked: None,
caption_set: false,
list,
icons: ShellIcons,
@@ -7034,6 +7037,48 @@ impl eframe::App for App {
if handled {
ctx.request_ui_pass(egui::ViewportId::ROOT);
}
+ // The clock: what must go on whatever the main window's state (#174). Minimized, egui
+ // runs no `ui`, and the queues, the Scheduler's starts and stops, the download limits,
+ // the kill switch, saving the list, the clipboard monitor, the update check, the tray and
+ // the taskbar's progress all stood still until the window was restored.
+ crate::settings::share_proxy(self.settings.proxy());
+ crate::settings::share_dns(self.settings.dns());
+ self.follow_assistive_technology(ctx);
+ self.network_adapter_tick(ctx);
+ self.debrid_tick();
+ self.poll(ctx);
+ // What failed in any window, told here (dialogs::tell).
+ if let Some((title, text)) = dialogs::told().pop() {
+ self.notice = Some((title, text));
+ }
+ self.auto_update_check(ctx);
+ self.apply_global_limit();
+ self.watch_clipboard(ctx);
+ self.tray(ctx);
+ // The taskbar button's green bar: everything running, as one.
+ #[cfg(windows)]
+ crate::win32::taskbar_progress(crate::MAIN_TITLE, self.overall_progress());
+ if self
+ .ticked
+ .is_none_or(|t| t.elapsed() > Duration::from_secs(2))
+ {
+ self.ticked = Some(Instant::now());
+ // For a crash report: what MDM has open and running (sent when it changes).
+ crate::crash::state(
+ self.items.len(),
+ self.items.iter().filter(|i| i.live.is_some()).count(),
+ self.queues.len(),
+ ctx.pixels_per_point(),
+ );
+ self.torrent_tick();
+ // Minimized, the windows these open (Download complete, a limit's notice, Download
+ // File Info for a copied link, an update) are made by a pass of the main window's
+ // UI, which egui runs then only when asked: every 2 s, as the clock repaints.
+ if ctx.input(|i| i.viewport().minimized == Some(true)) {
+ ctx.request_ui_pass(egui::ViewportId::ROOT);
+ }
+ }
+ ctx.request_repaint_after(Duration::from_secs(2));
}
fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
@@ -7048,31 +7093,15 @@ impl eframe::App for App {
if crate::offscreen() {
crate::win32::keep_from_foreground();
}
- crate::settings::share_proxy(self.settings.proxy());
- crate::settings::share_dns(self.settings.dns());
crate::crash::window("main");
let ctx = ui.ctx().clone();
- self.follow_assistive_technology(&ctx);
- self.network_adapter_tick(&ctx);
- self.debrid_tick();
dialogs::publish_main_rect(&ctx);
- // Incoming commands: `logic`, just before.
- self.poll(&ctx);
- // What failed in any window, told here (dialogs::tell).
- if let Some((title, text)) = dialogs::told().pop() {
- self.notice = Some((title, text));
- }
+ // Incoming commands and the clock (downloads, queues, Scheduler, saving…): `logic`, just
+ // before, which runs minimized too.
self.poll_picks(&ctx);
self.drop_target(&ctx);
self.main_drops(&ctx);
self.remember_layout(&ctx);
- self.auto_update_check(&ctx);
- self.apply_global_limit();
- self.watch_clipboard(&ctx);
- self.tray(&ctx);
- // The taskbar button's green bar: everything running, as one.
- #[cfg(windows)]
- crate::win32::taskbar_progress(crate::MAIN_TITLE, self.overall_progress());
// Light or dark: IDM follows Windows' app mode (checked every 2 s) unless View → Dark
// Mode support is off. Switches live (IDM asks to restart).
if self
@@ -7104,16 +7133,7 @@ impl eframe::App for App {
if changed {
ctx.request_repaint();
}
- // For a crash report: what MDM has open and running (sent when it changes).
- crate::crash::state(
- self.items.len(),
- self.items.iter().filter(|i| i.live.is_some()).count(),
- self.queues.len(),
- ctx.pixels_per_point(),
- );
- self.torrent_tick();
}
- ctx.request_repaint_after(Duration::from_secs(2));
egui::CentralPanel::no_frame()
.frame(egui::Frame::new().fill(chrome::WINDOW_BG()))
.show(ui, |ui| self.paint(ui));
diff --git a/crates/app/tests/minimized_clock.rs b/crates/app/tests/minimized_clock.rs
new file mode 100644
index 00000000..1698dfb2
--- /dev/null
+++ b/crates/app/tests/minimized_clock.rs
@@ -0,0 +1,157 @@
+//! #174: while the main window is minimized (not to the notification area), egui runs only the
+//! app's logic, never its UI. The queues, the Scheduler's starts and the list's saving ran in the
+//! UI, so a minimized MDM started nothing until it was restored. The real app, off the screens
+//! (MDM_OFFSCREEN), with a data folder of its own and the lab server on 127.0.0.1: its main
+//! window minimized (`/show minimized`, no input), a queue of three files, one at a time,
+//! scheduled to start a few seconds ahead. Every file must come down, one after the other, and
+//! the Download complete windows open.
+//!
+//! It opens windows, which needs OpenGL or Direct3D, so it runs on request:
+//! `cargo test -p mdm-app --test minimized_clock -- --ignored`.
+
+use std::path::Path;
+use std::process::{Child, Command};
+use std::time::{Duration, Instant};
+
+use mdm_labserver::{Config, LabServer};
+
+const APP: &str = env!("CARGO_BIN_EXE_misterdownloadmanager");
+
+/// The app's log so far (every file of `logs/`).
+fn log(data: &Path) -> String {
+ let mut all = String::new();
+ if let Ok(dir) = std::fs::read_dir(data.join("logs")) {
+ for f in dir.flatten() {
+ all += &std::fs::read_to_string(f.path()).unwrap_or_default();
+ }
+ }
+ all
+}
+
+/// Wait until `done` holds, failing if the app quits first or `wait` passes.
+fn wait_until(app: &mut Child, data: &Path, what: &str, wait: Duration, done: impl Fn() -> bool) {
+ let until = Instant::now() + wait;
+ loop {
+ let text = log(data);
+ assert!(!text.contains("panic"), "the app panicked:\n{text}");
+ if done() {
+ return;
+ }
+ if let Some(status) = app.try_wait().unwrap() {
+ panic!("the app closed ({status}) before {what}:\n{text}");
+ }
+ assert!(Instant::now() < until, "no {what} after {wait:?}:\n{text}");
+ std::thread::sleep(Duration::from_millis(250));
+ }
+}
+
+fn second_launch(data: &Path, args: &[&str]) {
+ let status = Command::new(APP)
+ .args(args)
+ .env("MDM_DATA_DIR", data)
+ .env("MDM_OFFSCREEN", "1")
+ .status()
+ .unwrap();
+ assert!(status.success(), "second launch {args:?}: {status}");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+#[ignore = "opens the app's windows (off-screen): needs OpenGL or Direct3D; run with --ignored"]
+async fn a_scheduled_queue_runs_while_minimized() {
+ let server = LabServer::start(Config::default()).await.unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let data = dir.path().join("data");
+ let files = dir.path().join("files");
+ std::fs::create_dir_all(&data).unwrap();
+ std::fs::create_dir_all(&files).unwrap();
+ let items: Vec<serde_json::Value> = (1..=3)
+ .map(|i| {
+ serde_json::json!({
+ "id": i,
+ "url": server.url(&format!("/gen/1M/q{i}.bin?seed={i}&rate=128K")),
+ "file_name": format!("q{i}.bin"),
+ "dest": files.join(format!("q{i}.bin")),
+ "size": null, "downloaded": 0, "status": "Queued", "category": "General",
+ "description": "", "resumable": false, "added": "Nov 06 10:00:00 2026",
+ "log": [],
+ })
+ })
+ .collect();
+ // The start: a little ahead, so the window is minimized well before it.
+ let at = chrono::Local::now() + chrono::Duration::seconds(12);
+ use chrono::Timelike;
+ let schedule = serde_json::json!({
+ "start_at": [at.hour(), at.minute(), at.second()], "days": [true, true, true, true, true, true, true],
+ });
+ let list = serde_json::json!({
+ "version": 2, "next_id": 4, "items": items,
+ "queues": [
+ { "name": "Main download queue", "files_at_once": 1, "items": [1, 2, 3],
+ "sync": false, "schedule": schedule },
+ { "name": "Synchronization queue", "files_at_once": 4, "items": [], "sync": true },
+ ],
+ "settings": {
+ "language": "en", "language_asked": true, "helpers_asked": true,
+ "extension_never_ask": true, "update_check": false, "clipboard_autostart": false,
+ "minimize_to_tray": false, "show_complete": true,
+ "torrent_dht": false, "torrent_lsd": false, "torrent_upnp": false,
+ "torrent_incoming": false,
+ },
+ });
+ std::fs::write(data.join("downloads.json"), list.to_string()).unwrap();
+ let result = tokio::task::spawn_blocking(move || {
+ let mut app = Command::new(APP)
+ .env("MDM_DATA_DIR", &data)
+ .env("MDM_OFFSCREEN", "1")
+ .spawn()
+ .unwrap();
+ let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let wait = Duration::from_secs(60);
+ wait_until(&mut app, &data, "main window", wait, || {
+ log(&data).contains("window opened: main")
+ });
+ second_launch(&data, &["/show", "minimized"]);
+ let done = |i: u32| {
+ std::fs::metadata(files.join(format!("q{i}.bin"))).is_ok_and(|m| m.len() == 1 << 20)
+ };
+ assert!(!done(1), "nothing before the scheduled start");
+ wait_until(&mut app, &data, "the three files", wait, || {
+ (1..=3).all(done)
+ });
+ wait_until(&mut app, &data, "Download complete", wait, || {
+ log(&data).contains("window opened: complete-3")
+ });
+ }));
+ let _ = Command::new(APP)
+ .arg("/exit")
+ .env("MDM_DATA_DIR", &data)
+ .env("MDM_OFFSCREEN", "1")
+ .status();
+ let until = Instant::now() + Duration::from_secs(15);
+ while app.try_wait().unwrap().is_none() && Instant::now() < until {
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ let _ = app.kill();
+ let _ = app.wait();
+ outcome
+ })
+ .await
+ .unwrap();
+ // One file at a time: each was asked for once its predecessor had come down.
+ let log = server.log();
+ let first_ask = |i: u32| {
+ log.iter()
+ .filter(|e| e.path.ends_with(&format!("q{i}.bin")))
+ .map(|e| e.t_start_ms)
+ .min()
+ };
+ if let Err(e) = result {
+ std::panic::resume_unwind(e);
+ }
+ let (a, b, c) = (first_ask(1), first_ask(2), first_ask(3));
+ assert!(
+ a.is_some() && b.is_some() && c.is_some(),
+ "{a:?} {b:?} {c:?}"
+ );
+ assert!(a <= b && b <= c, "in queue order: {a:?} {b:?} {c:?}");
+}