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
Linux: the tray icon is set up beside the window, which never waits for the session bus (fixes #828) (#858)
Ahmed Nefzaouiad65800d36dc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94eb2d31..08ce15af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- Linux: the window no longer freezes where the session bus doesn't answer (a session started without D-Bus, some minimal window managers, a bus that hangs). MDM made its tray icon on the window's own thread, and the tray library waits for the bus as the icon is made, so the window waited too, and reported "The window stopped responding". The icon is now set up beside the window, which opens at once and behaves meanwhile as it does with no tray (closing quits). A bus that answers later, however late, still brings the icon, and closing then hides the window in it ([#828](https://github.com/anefzaoui/misterdownloadmanager/issues/828)).- Looking up a video put online in the last two days no longer fails with "[Errno 13] Permission denied: 'C:\Program Files\Mister Download Manager\tmp…'" when MDM was opened from the Start menu. yt-dlp checks such a video's formats with a small file in the folder it was started in, and MDM started its helpers in its own, which is the install folder Windows doesn't let you write. yt-dlp, gallery-dl, ffmpeg and 7-Zip now run in your temporary folder; if that one can't be written, in a `work` folder of MDM's data folder, which the log names ([#834](https://github.com/anefzaoui/misterdownloadmanager/issues/834)).- A video a site sends through a program's address (`stream.php?file=lecture.mp4`, `remote_control.php`, many lecture and video sites do) is named by what it is, not by the program: MDM took the name and the type from the address's last part, so the file was saved as `stream.php`, the browser's media list showed **remote_control.php · PHP**, and the Download video window offered **PHP** and then failed ("The extracted extension (php) is unusual and will be skipped for safety reasons"). Now a name whose ending is a program's (`.php`, `.asp`, `.aspx`, `.jsp`, `.cgi` and the like), a page's or none at all takes its type from the address's `file=` name, else from what the server says it sends (video/mp4 is `.mp4`), else from the file's first bytes; a video from the browser whose address names nothing (a program, a bare number, `videoplayback`) is named by its page's title, with the **Prefix media file names with the page title** switch on or off; and a name the server gives (Content-Disposition) still wins. The media list shows that name and type (**Lecture 1.mp4 · MP4**), the button over a video says MP4 instead of PHP, and the Download video window saves such a video as an MP4. Only media, picture, document and archive types are taken this way, never a program's ([#695](https://github.com/anefzaoui/misterdownloadmanager/issues/695), [#800](https://github.com/anefzaoui/misterdownloadmanager/issues/800)).- Copying several links at once no longer opens **Download File Info** with all of them run together as one address (with **Offer to download links copied to the clipboard** on): a copied text with spaces or line breaks in it is not one link, and is left for **Add batch download from clipboard** ([#709](https://github.com/anefzaoui/misterdownloadmanager/issues/709)).diff --git a/ROADMAP.md b/ROADMAP.mdindex 63264c90..6634f1c8 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -557,6 +557,10 @@ Bug fixes from the first days of 0.5.0, a Safari extension, and more file types.These ship in the next version.+- ✅ Linux: no freeze of the window where the session bus doesn't answer (a session started+ without D-Bus, a bus that hangs): the tray icon is set up beside the window, which carries on+ without it until the bus answers, and gets it then, however late+ ([#828](https://github.com/anefzaoui/misterdownloadmanager/issues/828))- ✅ Looking up a new video (put online in the last two days) no longer fails with "Permissiondenied" in MDM's install folder: the helpers run in your temporary folder, or MDM's own ifthat one can't be written ([#834](https://github.com/anefzaoui/misterdownloadmanager/issues/834))diff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex b9addec0..b6ce0fbe 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -1002,6 +1002,10 @@ pub struct App {/// The notification-area icon (created on the first frame), the window hidden in it, and/// a real exit under way (closing the window otherwise only hides it, as IDM does).tray: Option<crate::tray::Tray>,+ /// Linux: the icon being made beside the window (#828: its library waits for the session+ /// bus); `tray` once it is.+ #[cfg(target_os = "linux")]+ tray_setup: Option<crate::tray::Setup>,tray_limiter: Option<bool>,/// When the main window was last seen focused: a tray click steals the focus first/// (the taskbar becomes foreground), so a click on a frontmost window reads as@@ -1624,6 +1628,8 @@ impl App {clip_asked: None,batch_clip: None,tray: None,+ #[cfg(target_os = "linux")]+ tray_setup: None,tray_limiter: None,tray_last_focused: None,// Started with the session (#226): hidden from the first frame.@@ -3719,10 +3725,33 @@ impl App {let wanted =!crate::offscreen() || std::env::var_os("MDM_TEST_TRAY").is_some_and(|v| v == "1");if self.tray.is_none() && self.tray_limiter.is_none() && wanted {- self.tray = crate::tray::Tray::new(ctx, self.settings.speed_limit_on);+ // Linux: made beside the window, which never waits for the session bus (#828); until+ // it is, the window behaves as with no tray host.+ #[cfg(target_os = "linux")]+ {+ self.tray_setup =+ Some(crate::tray::Setup::start(ctx, self.settings.speed_limit_on));+ }+ #[cfg(not(target_os = "linux"))]+ {+ self.tray = crate::tray::Tray::new(ctx, self.settings.speed_limit_on);+ if self.tray.is_some() {+ tracing::info!("tray icon shown");+ }+ }+ // The limiter the menu is made with (set again below once it changes).self.tray_limiter = Some(self.settings.speed_limit_on);- if self.tray.is_some() {- tracing::info!("tray icon shown");+ }+ #[cfg(target_os = "linux")]+ if let Some(setup) = &mut self.tray_setup {+ match setup.poll() {+ crate::tray::Came::Waiting => {}+ crate::tray::Came::Up(tray) => {+ tracing::info!("tray icon shown");+ self.tray = Some(tray);+ self.tray_setup = None;+ }+ crate::tray::Came::Failed => self.tray_setup = None,}}if let Some(t) = &self.traydiff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rsindex 2df20124..eb16540f 100644--- a/crates/app/src/tray.rs+++ b/crates/app/src/tray.rs@@ -7,6 +7,7 @@use std::sync::mpsc::{Receiver, Sender, channel};use std::sync::{Arc, Mutex};+mod beside;mod watch;pub use watch::Icon;@@ -40,7 +41,7 @@ pub enum TrayCmd {/// Whether a tray shows MDM's icon at all, so hiding a window there can be undone. Windows and/// macOS (the menu bar) always have one; on Linux only when a StatusNotifierItem host runs (#59),-/// asked each time: it may come and go.+/// asked each time: it may come and go. (Linux's icon itself is made beside the window: `Setup`.)pub fn available() -> bool {#[cfg(target_os = "linux")]return crate::unix::tray_host();@@ -85,23 +86,32 @@ pub fn on_close(keep_running: bool, tray: bool, icon: Icon, taskbar: bool) -> On/// The longest download name in the tray menu, in characters (the rest ends in "…").const MENU_NAME_MAX: usize = 48;+/// The tray icon as the window holds it: the icon and its menu (Windows, macOS: made on the+/// window's thread; Linux: on a thread of its own, see `Setup`), and the commands they send.pub struct Tray {+ native: Held,+ rx: Receiver<TrayCmd>,+ /// The tip shown and when, so the shell is told at most once a second.+ tip: std::cell::RefCell<(String, Option<std::time::Instant>)>,+ /// What Start and Stop main download queue were last set to (told only when it changes).+ queue_running: std::cell::Cell<Option<bool>>,+ /// The downloads "Downloads in progress" was last given (rebuilt only when they change).+ shown_downloads: std::cell::RefCell<Vec<(u64, String)>>,+}++/// The icon and its menu, as the system's tray library makes them.+struct Native {limiter_on: CheckMenuItem,limiter_off: CheckMenuItem,/// Start and Stop main download queue: one of them enabled, as the queue runs.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>)>,- rx: Receiver<TrayCmd>,/// "Downloads in progress": one entry per running download, rebuilt when they change.downloads: Submenu,- shown_downloads: std::cell::RefCell<Vec<(u64, String)>>,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)>,@@ -129,6 +139,209 @@ enum Entry {}impl Tray {+ /// The icon and its menu; events wake `ctx`. None if the shell refuses the icon (logged).+ /// Linux makes it beside the window instead: [`Setup`].+ #[cfg(not(target_os = "linux"))]+ pub fn new(ctx: &egui::Context, limiter: bool) -> Option<Tray> {+ let (tx, rx) = channel();+ Some(Tray::with(Native::new(ctx, limiter, tx)?, rx))+ }++ fn with(native: Held, rx: Receiver<TrayCmd>) -> Tray {+ Tray {+ native,+ rx,+ tip: Default::default(),+ queue_running: std::cell::Cell::new(None),+ shown_downloads: Default::default(),+ }+ }++ /// Run `job` on the icon: here, or on its own thread on Linux (never waiting for it there).+ fn at(&self, job: impl FnOnce(&Native) + Send + 'static) {+ #[cfg(not(target_os = "linux"))]+ job(&self.native);+ #[cfg(target_os = "linux")]+ self.native.run(job);+ }++ /// What the shell says of the icon: [`Native::icon`].+ #[cfg(any(target_os = "windows", target_os = "macos"))]+ pub fn icon(&self) -> Icon {+ self.native.icon()+ }++ /// [`Native::icon_now`].+ #[cfg(any(target_os = "windows", target_os = "macos"))]+ pub fn icon_now(&self) -> Icon {+ self.native.icon_now()+ }++ /// [`Native::rescue`].+ #[cfg(windows)]+ pub fn rescue(&self) -> bool {+ self.native.rescue()+ }++ /// The commands since the last call.+ pub fn poll(&self) -> Vec<TrayCmd> {+ self.rx.try_iter().collect()+ }++ /// Translate the menu again (the interface language changed).+ pub fn relabel(&self) {+ self.at(Native::relabel);+ }++ /// Keep Start / Stop main download queue in step with the queue (the menu is only told+ /// when it changes).+ pub fn set_queue(&self, running: bool) {+ if self.queue_running.replace(Some(running)) != Some(running) {+ self.at(move |n| n.set_queue(running));+ }+ }++ /// The icon's tip: the app's name, and while downloads run how many and how fast.+ pub fn set_tooltip(&self, tip: &str) {+ let mut last = self.tip.borrow_mut();+ let due = last+ .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.native.tip(tip) {+ return;+ }+ #[cfg(not(windows))]+ {+ let tip = tip.to_owned();+ self.at(move |n| {+ n.tip(&tip);+ });+ }+ *last = (tip.to_owned(), Some(std::time::Instant::now()));+ }+ }++ /// "Downloads in progress": the running downloads (id, name), the menu rebuilt only when they+ /// change; greyed when none runs.+ pub fn set_downloads(&self, running: &[(u64, String)]) {+ if *self.shown_downloads.borrow() == running {+ return;+ }+ let running = running.to_vec();+ *self.shown_downloads.borrow_mut() = running.clone();+ self.at(move |n| n.set_downloads(&running));+ }++ /// Keep the Speed Limiter checks in step with the app.+ pub fn set_limiter(&self, on: bool) {+ self.at(move |n| n.set_limiter(on));+ }+}++/// The icon as [`Tray`] holds it: itself (Windows, macOS), or the thread that keeps it (Linux).+#[cfg(not(target_os = "linux"))]+type Held = Native;+#[cfg(target_os = "linux")]+type Held = beside::Beside<Native>;++/// Linux's tray icon on its way (#828): made on a thread of its own, as its library waits for the+/// session bus, for ever where none answers. Until it is made the window behaves as with no tray+/// host; [`Setup::poll`] hands it over once it is, however late.+#[cfg(target_os = "linux")]+pub struct Setup {+ native: Option<beside::Beside<Native>>,+ rx: Option<Receiver<TrayCmd>>,+ started: std::time::Instant,+ /// The interface language the menu was made in, to translate it again if it changed since.+ lang: &'static str,+ /// The phase last seen, to log each change once.+ told: beside::Phase,+}++/// What [`Setup::poll`] found.+#[cfg(target_os = "linux")]+pub enum Came {+ /// Not yet: the window behaves as with no tray host.+ Waiting,+ /// The icon, made.+ Up(Tray),+ /// No icon this run (logged).+ Failed,+}++#[cfg(target_os = "linux")]+impl Setup {+ /// Start making the icon and its menu beside the window; its events, and its coming, wake+ /// `ctx`.+ pub fn start(ctx: &egui::Context, limiter: bool) -> Setup {+ let (tx, rx) = channel();+ let made = ctx.clone();+ let wake = ctx.clone();+ let native = beside::Beside::start(+ "tray icon",+ move || Native::new(&made, limiter, tx),+ move || wake.request_repaint(),+ );+ // To log a long wait once it is long, even with nothing else to draw.+ ctx.request_repaint_after(beside::WAIT);+ Setup {+ native: Some(native),+ rx: Some(rx),+ started: std::time::Instant::now(),+ lang: crate::i18n::code(),+ told: beside::Phase::Waiting,+ }+ }++ /// Whether the icon is made. Never waits for it.+ pub fn poll(&mut self) -> Came {+ let Some(native) = &self.native else {+ return Came::Failed;+ };+ let waited = self.started.elapsed();+ let phase = beside::phase(native.made(), waited);+ let was = std::mem::replace(&mut self.told, phase);+ match phase {+ beside::Phase::Waiting => Came::Waiting,+ beside::Phase::GaveUp => {+ if was != phase {+ tracing::warn!(+ "tray icon: the session bus hasn't answered in {} s: carrying on without the icon (closing quits) until it does",+ beside::WAIT.as_secs()+ );+ }+ Came::Waiting+ }+ beside::Phase::Failed => {+ self.native = None;+ Came::Failed+ }+ beside::Phase::Up => {+ let (Some(native), Some(rx)) = (self.native.take(), self.rx.take()) else {+ return Came::Failed;+ };+ if was == beside::Phase::GaveUp {+ tracing::info!(+ "tray icon: the session bus answered late, {} ms on",+ waited.as_millis()+ );+ } else {+ tracing::info!("tray icon: made in {} ms", waited.as_millis());+ }+ let tray = Tray::with(native, rx);+ if crate::i18n::code() != self.lang {+ tray.relabel();+ }+ Came::Up(tray)+ }+ }+ }+}++impl Native {/// 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@@ -194,8 +407,9 @@ impl Tray {self.seen.get()}- /// The icon and its menu; events wake `ctx`. None if the shell refuses the icon (logged).- pub fn new(ctx: &egui::Context, limiter: bool) -> Option<Tray> {+ /// The icon and its menu; events go to `tx` and wake `ctx`. None if the shell refuses the icon+ /// (logged).+ fn new(ctx: &egui::Context, limiter: bool, tx: Sender<TrayCmd>) -> Option<Native> {let menu = Menu::new();let mut items = Vec::new();let mut labels = Vec::new();@@ -292,7 +506,6 @@ impl Tray {)};- let (tx, rx) = channel();let wake = |tx: &Sender<TrayCmd>, ctx: &egui::Context| (tx.clone(), ctx.clone());let (icon_tx, icon_ctx) = wake(&tx, ctx);TrayIconEvent::set_event_handler(Some(move |e: TrayIconEvent| {@@ -330,17 +543,13 @@ impl Tray {labels.push((Entry::Sub(downloads.clone()), downloads_label));labels.push((Entry::Check(limiter_on.clone()), on_label));labels.push((Entry::Check(limiter_off.clone()), off_label));- Some(Tray {+ Some(Native {tray,- tip: Default::default(),limiter_on,limiter_off,start_queue,stop_queue,- queue_running: std::cell::Cell::new(None),- rx,downloads,- shown_downloads: Default::default(),download_ids,labels,#[cfg(target_os = "macos")]@@ -354,13 +563,8 @@ impl Tray {})}- /// The commands since the last call.- pub fn poll(&self) -> Vec<TrayCmd> {- self.rx.try_iter().collect()- }-/// Translate the menu again (the interface language changed).- pub fn relabel(&self) {+ fn relabel(&self) {for (entry, source) in &self.labels {let text = crate::i18n::t(source);match entry {@@ -371,39 +575,26 @@ impl Tray {}}- /// Keep Start / Stop main download queue in step with the queue (the menu is only told- /// when it changes).- pub fn set_queue(&self, running: bool) {- if self.queue_running.replace(Some(running)) != Some(running) {- self.start_queue.set_enabled(!running);- self.stop_queue.set_enabled(running);- }+ /// Start / Stop main download queue, as the queue runs.+ fn set_queue(&self, running: bool) {+ self.start_queue.set_enabled(!running);+ self.stop_queue.set_enabled(running);}- /// The icon's tip: the app's name, and while downloads run how many and how fast.- pub fn set_tooltip(&self, tip: &str) {- let mut last = self.tip.borrow_mut();- let due = last- .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))]+ /// Set the icon's tip; false if the shell didn't take it (Windows: the watcher was busy, asked+ /// again at the next frame).+ fn tip(&self, tip: &str) -> bool {+ #[cfg(windows)]+ return self.watch.tip(tip);+ #[cfg(not(windows))]+ {let _ = self.tray.set_tooltip(Some(tip));- *last = (tip.to_owned(), Some(std::time::Instant::now()));+ true}}- /// "Downloads in progress": the running downloads (id, name), the menu rebuilt only when they- /// change; greyed when none runs.- pub fn set_downloads(&self, running: &[(u64, String)]) {- if *self.shown_downloads.borrow() == running {- return;- }+ /// "Downloads in progress": the running downloads (id, name); greyed when none runs.+ fn set_downloads(&self, running: &[(u64, String)]) {for _ in 0..self.downloads.items().len() {let _ = self.downloads.remove_at(0);}@@ -417,11 +608,10 @@ impl Tray {*d = ids;}self.downloads.set_enabled(!running.is_empty());- *self.shown_downloads.borrow_mut() = running.to_vec();}- /// Keep the Speed Limiter checks in step with the app.- pub fn set_limiter(&self, on: bool) {+ /// The Speed Limiter checks.+ fn set_limiter(&self, on: bool) {self.limiter_on.set_checked(on);self.limiter_off.set_checked(!on);}diff --git a/crates/app/src/tray/beside.rs b/crates/app/src/tray/beside.rsnew file mode 100644index 00000000..c84f67cd--- /dev/null+++ b/crates/app/src/tray/beside.rs@@ -0,0 +1,204 @@+//! Linux's tray icon, set up and kept on a thread of its own (#828). Its library (tray-icon over+//! ksni) connects to the session bus as the icon is made, and waits for the bus at each change of+//! the icon after: for ever where the bus doesn't answer (a session started without D-Bus, a bus+//! that hangs), and the window froze while it waited. So a thread beside the window makes the icon+//! and keeps it ([`Beside`]), the window hands it each change as a job and never waits for one, and+//! it reads how far the making got ([`Beside::made`]), which never waits either. The rule of the+//! notification-area icon's questions on Windows (`watch.rs`, #747) and of the clipboard's reads.+//!+//! Until the icon is made the window behaves as with no tray host (closing quits, #59). After+//! [`WAIT`] it says in the log that it carries on without one ([`Phase::GaveUp`]); a bus that+//! answers later still brings the icon, and closing then hides the window in it.++// Only Linux makes its tray here; the state machine is tested everywhere.+#![cfg_attr(not(target_os = "linux"), allow(dead_code))]++use std::sync::Arc;+use std::sync::atomic::{AtomicU8, Ordering};+use std::sync::mpsc::{Sender, channel};+use std::time::Duration;++/// How long the window waits for the icon before it says it carries on without it.+pub const WAIT: Duration = Duration::from_secs(5);++/// How far the thread got in making the icon.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Made {+ /// Still making it (waiting for the bus).+ Not,+ /// Made: it takes jobs.+ Up,+ /// The system refused it (no bus at all, no picture): logged by the maker.+ Failed,+}++/// What the window makes of [`Made`] after `waited`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Phase {+ /// Being made, for less than [`WAIT`]: the window behaves as with no tray host.+ Waiting,+ /// Not made after [`WAIT`]: the window carries on without it, and still takes it if it comes.+ GaveUp,+ /// The icon is there to use.+ Up,+ /// No icon this run.+ Failed,+}++/// The window's reading of `made` after `waited` since the thread started.+pub fn phase(made: Made, waited: Duration) -> Phase {+ match made {+ Made::Up => Phase::Up,+ Made::Failed => Phase::Failed,+ Made::Not if waited >= WAIT => Phase::GaveUp,+ Made::Not => Phase::Waiting,+ }+}++const NOT: u8 = 0;+const UP: u8 = 1;+const FAILED: u8 = 2;++/// A change for the thing the thread keeps.+type Job<T> = Box<dyn FnOnce(&T) + Send>;++/// A thing made and kept on a thread of its own (`T` never leaves it: tray-icon's icon and menu+/// can't cross threads); the window hands it jobs.+pub struct Beside<T> {+ made: Arc<AtomicU8>,+ jobs: Sender<Job<T>>,+}++impl<T: 'static> Beside<T> {+ /// Make the thing with `make` on a thread named `name`, then run the jobs the window hands it+ /// until the window drops this (the thing is then dropped there too, never waited for).+ /// `wake` is told once `make` returns.+ pub fn start(+ name: &str,+ make: impl FnOnce() -> Option<T> + Send + 'static,+ wake: impl FnOnce() + Send + 'static,+ ) -> Beside<T> {+ let made = Arc::new(AtomicU8::new(NOT));+ let (jobs, rx) = channel::<Job<T>>();+ let state = made.clone();+ let spawned = std::thread::Builder::new()+ .name(name.into())+ .spawn(move || {+ let thing = make();+ state.store(if thing.is_some() { UP } else { FAILED }, Ordering::Release);+ wake();+ if let Some(thing) = thing {+ for job in rx {+ job(&thing);+ }+ }+ });+ if let Err(e) = spawned {+ tracing::warn!("{name}: no thread to make it on ({e})");+ made.store(FAILED, Ordering::Release);+ }+ Beside { made, jobs }+ }++ /// How far the making got. Never waits.+ pub fn made(&self) -> Made {+ match self.made.load(Ordering::Acquire) {+ UP => Made::Up,+ FAILED => Made::Failed,+ _ => Made::Not,+ }+ }++ /// Have `job` run on the thing, in the order given. Never waits (a thread stuck on the bus+ /// only holds up the jobs after it).+ pub fn run(&self, job: impl FnOnce(&T) + Send + 'static) {+ let _ = self.jobs.send(Box::new(job));+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::Cell;+ use std::sync::mpsc;+ use std::time::Instant;++ /// The window's reading of the thread's progress: waiting, then giving up after WAIT; made+ /// or refused whenever it comes, a late icon included.+ #[test]+ fn the_window_waits_a_few_seconds_then_carries_on_and_still_takes_a_late_icon() {+ assert_eq!(phase(Made::Not, Duration::ZERO), Phase::Waiting);+ assert_eq!(+ phase(Made::Not, WAIT - Duration::from_millis(1)),+ Phase::Waiting+ );+ assert_eq!(phase(Made::Not, WAIT), Phase::GaveUp);+ assert_eq!(phase(Made::Not, Duration::from_secs(3600)), Phase::GaveUp);+ for waited in [Duration::ZERO, WAIT, Duration::from_secs(3600)] {+ assert_eq!(phase(Made::Up, waited), Phase::Up, "{waited:?}");+ assert_eq!(phase(Made::Failed, waited), Phase::Failed, "{waited:?}");+ }+ }++ /// A thing whose making waits for the test (for ever, if the test never says).+ fn held(until: mpsc::Receiver<bool>) -> impl FnOnce() -> Option<Cell<u32>> + Send + 'static {+ move || until.recv().ok().and_then(|up| up.then(|| Cell::new(0)))+ }++ /// A bus that never answers holds up nothing: the window reads "not made" at once, every+ /// time, its jobs are taken at once, and dropping the handle doesn't wait for the thread.+ #[test]+ fn a_bus_that_never_answers_holds_up_nothing() {+ let (_never, until) = mpsc::channel();+ let b = Beside::start("test tray", held(until), || {});+ let start = Instant::now();+ for _ in 0..10_000 {+ assert_eq!(b.made(), Made::Not);+ b.run(|n: &Cell<u32>| n.set(n.get() + 1));+ }+ drop(b);+ assert!(start.elapsed() < Duration::from_secs(2));+ }++ /// A late answer: the window is woken, reads "up", and the jobs it handed meanwhile and+ /// after run on the thing, in order.+ #[test]+ fn a_late_answer_brings_the_icon_and_runs_the_jobs_in_order() {+ let (answer, until) = mpsc::channel();+ let (woke, woken) = mpsc::channel();+ let b = Beside::start("test tray", held(until), move || {+ let _ = woke.send(());+ });+ let (seen, saw) = mpsc::channel();+ let tell = seen.clone();+ b.run(move |n: &Cell<u32>| {+ n.set(n.get() + 1);+ let _ = tell.send(n.get());+ });+ assert!(woken.recv_timeout(Duration::from_millis(200)).is_err());+ assert_eq!(b.made(), Made::Not);+ answer.send(true).unwrap();+ woken.recv_timeout(Duration::from_secs(5)).unwrap();+ assert_eq!(b.made(), Made::Up);+ b.run(move |n: &Cell<u32>| {+ n.set(n.get() + 10);+ let _ = seen.send(n.get());+ });+ assert_eq!(saw.recv_timeout(Duration::from_secs(5)).unwrap(), 1);+ assert_eq!(saw.recv_timeout(Duration::from_secs(5)).unwrap(), 11);+ }++ /// A refused icon (no bus at all): the window is woken and reads "failed"; jobs go nowhere.+ #[test]+ fn a_refused_icon_is_failed_and_jobs_go_nowhere() {+ let (answer, until) = mpsc::channel();+ let (woke, woken) = mpsc::channel();+ let b = Beside::start("test tray", held(until), move || {+ let _ = woke.send(());+ });+ answer.send(false).unwrap();+ woken.recv_timeout(Duration::from_secs(5)).unwrap();+ assert_eq!(b.made(), Made::Failed);+ b.run(|_: &Cell<u32>| panic!("no thing to run on"));+ }+}