Skip to content

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

Linux: the window no longer freezes when the system's sleep or keychain service is slow (#242)

Ahmed Nefzaoui09623dca83ea
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 45e04bab..0302a118 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -521,6 +521,17 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **The window no longer freezes when the system's sleep or keychain service is slow**
+ (follows [#222](https://github.com/anefzaoui/misterdownloadmanager/issues/222)): a queue set to
+ **Wake the computer to run this queue** asks the system to keep the computer awake while it
+ runs. On Linux that is logind, which can be slow to answer just after the computer wakes,
+ exactly when such a queue starts, and MDM waited for it on the window's own thread (asking
+ again every 5 seconds while it refused). It is now asked in the background, on every system;
+ the queue's downloads, retries and log lines are the same. A keyring that doesn't answer at
+ start (a stopped GNOME Keyring) is now waited for once, at most 5 seconds, instead of once per
+ saved password, and saving the list no longer asks it at all. On Linux the check for a tray to
+ hide windows in, and in Download File Info the check that **Save As** isn't a folder (slow on a
+ network share that doesn't answer), no longer run on the window's thread on every frame.
- **Linux: Dark Mode support follows XFCE, MATE and other desktops too**
([#156](https://github.com/anefzaoui/misterdownloadmanager/issues/156)): MDM followed the
desktop's light or dark setting only where the freedesktop portal answers (GNOME, KDE,
diff --git a/ROADMAP.md b/ROADMAP.md
index 3320dd4b..cfa6f38f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -13,6 +13,11 @@ Everything below ships together, in one release, as version 0.3.0.
### Done
+- ✅ The window no longer freezes on Linux when the system's sleep service (logind) or keyring
+ (Secret Service) is slow or doesn't answer: keeping the computer awake for a woken queue is
+ asked in the background, a keyring that doesn't answer at start is waited for once instead of
+ once per saved password, and the tray check and Download File Info's Save As check no longer
+ wait on every frame (follows [#222](https://github.com/anefzaoui/misterdownloadmanager/issues/222))
- ✅ Linux: Dark Mode support follows the desktop's dark or light theme on XFCE, MATE and others
without the portal's setting, and on GNOME without the portal, live
([#156](https://github.com/anefzaoui/misterdownloadmanager/issues/156))
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index b5cf4e1c..51f1ac66 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -676,6 +676,9 @@ pub struct FileInfo {
/// "Download through …" unticked: downloaded directly instead (`Item::direct`). Unticked
/// from the start when the browser had already started the download.
pub direct: bool,
+ /// Whether Save As names a folder, looked at off the window's thread: it is asked every
+ /// frame, and a folder on a network share that doesn't answer would freeze the window.
+ dest_dir: crate::launch::Asked<PathBuf, bool>,
}
pub enum Start {
@@ -730,6 +733,7 @@ impl FileInfo {
None => (start_probe(rt, ctx, &new.url, &request), None),
};
FileInfo {
+ dest_dir: Default::default(),
url_text: new.url.to_string(),
url_bad: false,
focused: false,
@@ -1166,10 +1170,23 @@ impl FileInfo {
let name_bad = {
let typed = self.save_as.trim();
let dest = self.dest();
+ // A local disk answers within the wait; a share that doesn't reads as no
+ // folder meanwhile (the download says so if it can't write there).
+ let folder = || {
+ self.dest_dir
+ .get(
+ &dest,
+ std::time::Duration::from_secs(1),
+ std::time::Duration::from_millis(50),
+ Some(ui.ctx()),
+ |d| d.is_dir(),
+ )
+ .unwrap_or(false)
+ };
typed.is_empty()
|| typed.ends_with(['\\', '/'])
|| dest.file_name().is_none()
- || dest.is_dir()
+ || folder()
};
let blocked = if self.url_bad {
Some("Invalid address")
diff --git a/crates/app/src/launch.rs b/crates/app/src/launch.rs
index 95af00e3..4c9eadc8 100644
--- a/crates/app/src/launch.rs
+++ b/crates/app/src/launch.rs
@@ -7,6 +7,7 @@
use std::ffi::OsStr;
use std::io::Read;
use std::process::{Child, Command, ExitStatus, Output, Stdio};
+use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
/// Run `cmd` quietly on a thread of its own, waiting at most `limit` for it; when it can't
@@ -47,6 +48,105 @@ pub fn open(target: impl AsRef<OsStr>) {
}
}
+/// An answer the system may take its time to give (a D-Bus call, a look at a folder that may be
+/// on a network share), asked on a thread of its own and kept: a window that needs it every frame
+/// reads the last answer, and never waits for more than it says (the same rule as the programs
+/// above, for calls).
+pub struct Asked<K, T> {
+ shared: Arc<(Mutex<AskedState<K, T>>, Condvar)>,
+}
+
+struct AskedState<K, T> {
+ /// The last answer: for which key, what, and when it came.
+ answer: Option<(K, T, Instant)>,
+ /// A question is on its way (one at a time: a call that hangs isn't asked again meanwhile).
+ asking: bool,
+}
+
+impl<K, T> Default for Asked<K, T> {
+ fn default() -> Self {
+ Asked {
+ shared: Arc::new((
+ Mutex::new(AskedState {
+ answer: None,
+ asking: false,
+ }),
+ Condvar::new(),
+ )),
+ }
+ }
+}
+
+impl<K, T> Asked<K, T>
+where
+ K: Clone + PartialEq + Send + 'static,
+ T: Clone + PartialEq + Send + 'static,
+{
+ /// The answer for `key`. The last one is asked again (`ask`, on a thread of its own) once it
+ /// is older than `every` or was for another key. None while there is none for `key` yet,
+ /// after waiting at most `wait` for it (zero: not at all). `repaint` is repainted when an
+ /// answer comes that differs from the last one, so the window shows it.
+ pub fn get(
+ &self,
+ key: &K,
+ every: Duration,
+ wait: Duration,
+ repaint: Option<&egui::Context>,
+ ask: impl FnOnce(&K) -> T + Send + 'static,
+ ) -> Option<T> {
+ let (lock, cv) = &*self.shared;
+ let mut s = lock.lock().unwrap_or_else(|e| e.into_inner());
+ let fresh = s
+ .answer
+ .as_ref()
+ .is_some_and(|(k, _, at)| k == key && at.elapsed() < every);
+ if !fresh && !s.asking {
+ s.asking = true;
+ let shared = self.shared.clone();
+ let key = key.clone();
+ let repaint = repaint.cloned();
+ let started = std::thread::Builder::new()
+ .name("asked".into())
+ .spawn(move || {
+ let value = ask(&key);
+ let (lock, cv) = &*shared;
+ let mut s = lock.lock().unwrap_or_else(|e| e.into_inner());
+ let changed = s
+ .answer
+ .as_ref()
+ .is_none_or(|(k, v, _)| *k != key || *v != value);
+ s.answer = Some((key, value, Instant::now()));
+ s.asking = false;
+ cv.notify_all();
+ drop(s);
+ if changed && let Some(ctx) = repaint {
+ ctx.request_repaint();
+ }
+ });
+ if let Err(e) = started {
+ tracing::warn!("asked: no thread to ask on: {e}");
+ s.asking = false;
+ }
+ }
+ let start = Instant::now();
+ loop {
+ if let Some((k, v, _)) = &s.answer
+ && k == key
+ {
+ return Some(v.clone());
+ }
+ let left = wait.saturating_sub(start.elapsed());
+ if left.is_zero() || !s.asking {
+ return None;
+ }
+ s = cv
+ .wait_timeout(s, left)
+ .unwrap_or_else(|e| e.into_inner())
+ .0;
+ }
+ }
+}
+
/// Run `cmd` quietly, waiting at most `limit` for it: true when it ran and succeeded. One that
/// runs out of time is ended. For a thread other than the window's.
pub fn run_within(cmd: &mut Command, limit: Duration) -> bool {
@@ -209,3 +309,100 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
}
+
+#[cfg(test)]
+mod asked_tests {
+ use super::*;
+ use std::sync::atomic::{AtomicU32, Ordering};
+
+ const NO_WAIT: Duration = Duration::ZERO;
+
+ #[test]
+ fn a_call_that_hangs_never_holds_the_window_and_is_asked_once() {
+ let asked = Asked::<(), bool>::default();
+ let calls = Arc::new(AtomicU32::new(0));
+ let ask = |calls: &Arc<AtomicU32>| {
+ let calls = calls.clone();
+ move |_: &()| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ std::thread::sleep(Duration::from_secs(3));
+ true
+ }
+ };
+ let start = Instant::now();
+ let first = asked.get(
+ &(),
+ Duration::ZERO,
+ Duration::from_millis(100),
+ None,
+ ask(&calls),
+ );
+ assert_eq!(first, None);
+ // Waited what it said, not for the call.
+ assert!(
+ start.elapsed() < Duration::from_millis(600),
+ "{:?}",
+ start.elapsed()
+ );
+ // The next frames: at once, and the hanging call isn't asked again meanwhile.
+ for _ in 0..50 {
+ let t = Instant::now();
+ assert_eq!(
+ asked.get(&(), Duration::ZERO, NO_WAIT, None, ask(&calls)),
+ None
+ );
+ assert!(t.elapsed() < Duration::from_millis(50));
+ }
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn pending_then_done_then_asked_again_when_stale() {
+ let asked = Asked::<(), u32>::default();
+ let n = Arc::new(AtomicU32::new(0));
+ let ask = |n: &Arc<AtomicU32>| {
+ let n = n.clone();
+ move |_: &()| n.fetch_add(1, Ordering::SeqCst) + 1
+ };
+ // A quick answer is waited for.
+ let every = Duration::from_millis(200);
+ let wait = Duration::from_secs(2);
+ assert_eq!(asked.get(&(), every, wait, None, ask(&n)), Some(1));
+ // Fresh: kept, not asked again.
+ assert_eq!(asked.get(&(), every, NO_WAIT, None, ask(&n)), Some(1));
+ assert_eq!(n.load(Ordering::SeqCst), 1);
+ std::thread::sleep(Duration::from_millis(250));
+ // Stale: the last answer at once, a new one asked meanwhile.
+ assert_eq!(asked.get(&(), every, NO_WAIT, None, ask(&n)), Some(1));
+ let start = Instant::now();
+ while asked.get(&(), every, NO_WAIT, None, ask(&n)) != Some(2) {
+ assert!(
+ start.elapsed() < Duration::from_secs(2),
+ "never asked again"
+ );
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+
+ #[test]
+ fn another_key_has_no_answer_until_its_own() {
+ let asked = Asked::<String, usize>::default();
+ let len = |k: &String| k.len();
+ let wait = Duration::from_secs(2);
+ let long = Duration::from_secs(60);
+ assert_eq!(asked.get(&"ab".into(), long, wait, None, len), Some(2));
+ assert_eq!(asked.get(&"abcd".into(), long, wait, None, len), Some(4));
+ // An answer that is slow for the new key: none for it (never the old key's).
+ let slow = |k: &String| {
+ std::thread::sleep(Duration::from_millis(300));
+ k.len()
+ };
+ assert_eq!(asked.get(&"x".into(), long, NO_WAIT, None, slow), None);
+ let start = Instant::now();
+ while asked.get(&"x".into(), long, NO_WAIT, None, slow).is_none() {
+ assert!(start.elapsed() < Duration::from_secs(3));
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert_eq!(asked.get(&"x".into(), long, NO_WAIT, None, slow), Some(1));
+ }
+}
diff --git a/crates/app/src/secrets.rs b/crates/app/src/secrets.rs
index bb9b6539..ea58a602 100644
--- a/crates/app/src/secrets.rs
+++ b/crates/app/src/secrets.rs
@@ -199,13 +199,23 @@ impl Vault {
}
/// A reference read from the settings: its secret, or "" when it can't be read now (the
- /// reference is then kept for the next save).
+ /// reference is then kept for the next save). The list is read before the window opens:
+ /// once the keychain didn't answer (none, or none within the Secret Service's 5 s), the
+ /// other references aren't asked this session, so MDM waits for it once, not once each.
pub fn open(&self, stored: &str) -> String {
let Some(target) = Target::parse(stored) else {
tracing::warn!("sign-ins: a keychain reference that doesn't read");
return String::new();
};
- match self.store.read(&target.service, &target.account) {
+ let outcome = if self.lock().kept == Some(Kept::Missing) {
+ Err(Fault::Missing)
+ } else {
+ self.store.read(&target.service, &target.account)
+ };
+ if outcome == Err(Fault::Missing) {
+ self.lock().kept.get_or_insert(Kept::Missing);
+ }
+ match outcome {
Ok(Some(secret)) => {
let mut s = self.lock();
s.unread.remove(target.key());
@@ -550,7 +560,8 @@ thread_local! {
/// Serialize settings made ready for the disk ([`crate::settings::Settings::for_disk`]): their
/// secret fields already hold what is written (a reference or a sealed secret) and go as they
-/// are.
+/// are. Settings read inside it are read as the disk has them, the same way: nothing is opened
+/// nor asked of the keychain (a check that a list reads).
pub fn prepared<R>(f: impl FnOnce() -> R) -> R {
struct Reset;
impl Drop for Reset {
@@ -601,6 +612,47 @@ impl Memory {
}
}
+/// A keychain that takes `delay` to answer each call, and answers as `inner` does: one that
+/// hangs (a stopped gnome-keyring) until the Secret Service's timeout, for tests.
+#[cfg(test)]
+pub struct Slow {
+ pub inner: Arc<Memory>,
+ pub delay: std::time::Duration,
+ pub calls: std::sync::atomic::AtomicU32,
+}
+
+#[cfg(test)]
+impl Slow {
+ fn call(&self) {
+ self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ std::thread::sleep(self.delay);
+ }
+}
+
+#[cfg(test)]
+impl Store for Arc<Slow> {
+ fn probe(&self, service: &str) -> Result<(), Fault> {
+ self.call();
+ self.inner.probe(service)
+ }
+ fn read(&self, service: &str, account: &str) -> Result<Option<String>, Fault> {
+ self.call();
+ self.inner.read(service, account)
+ }
+ fn write(&self, service: &str, account: &str, label: &str, secret: &str) -> Result<(), Fault> {
+ self.call();
+ self.inner.write(service, account, label, secret)
+ }
+ fn delete(&self, service: &str, account: &str) -> Result<(), Fault> {
+ self.call();
+ self.inner.delete(service, account)
+ }
+ fn list(&self, service: &str) -> Result<Vec<String>, Fault> {
+ self.call();
+ self.inner.list(service)
+ }
+}
+
#[cfg(test)]
impl Store for Arc<Memory> {
fn probe(&self, _: &str) -> Result<(), Fault> {
@@ -914,6 +966,83 @@ mod tests {
});
}
+ /// The keychain hangs at start (a stopped gnome-keyring: each call ends at the Secret
+ /// Service's timeout): the list's references wait for it once, not once each, and the
+ /// secrets come back once it answers again.
+ #[test]
+ fn a_keychain_that_doesnt_answer_is_waited_for_once() {
+ use std::sync::atomic::Ordering;
+ let mem = Arc::new(Memory::default());
+ let first = vault_on(&mem, "aaaa0011");
+ let saved = with_vault(&first, || {
+ let _ = on_disk(&sample());
+ first.run_once();
+ on_disk(&sample())
+ });
+ assert_eq!(saved.matches(REF).count(), 3);
+ *mem.fault.lock().unwrap() = Some(Fault::Missing);
+ let slow = Arc::new(Slow {
+ inner: mem.clone(),
+ delay: std::time::Duration::from_millis(400),
+ calls: Default::default(),
+ });
+ let next = Arc::new(Vault::new(
+ Box::new(slow.clone()),
+ "MDM-test-unit",
+ "aaaa0011",
+ true,
+ false,
+ ));
+ let start = std::time::Instant::now();
+ let loaded = with_vault(&next, || read(&saved));
+ let took = start.elapsed();
+ assert_eq!(slow.calls.load(Ordering::SeqCst), 1, "asked once");
+ assert!(took < std::time::Duration::from_millis(1000), "{took:?}");
+ assert!(loaded.proxy_pass.is_empty());
+ assert_eq!(next.kept(), Kept::Missing);
+ // Saved meanwhile: the references as they were, nothing asked of the keychain.
+ assert_eq!(with_vault(&next, || on_disk(&loaded)), saved);
+ next.run_once();
+ assert_eq!(slow.calls.load(Ordering::SeqCst), 1);
+ // The next start, with a keychain that answers: back.
+ *mem.fault.lock().unwrap() = None;
+ assert_eq!(
+ with_vault(&vault_on(&mem, "aaaa0011"), || read(&saved)),
+ sample()
+ );
+ }
+
+ /// Checking that the list on the disk reads (before a save keeps it as a generation) opens
+ /// none of its secrets: no keychain call on every save, nor on the window's last save.
+ #[test]
+ fn checking_a_list_asks_no_keychain() {
+ use std::sync::atomic::Ordering;
+ let mem = Arc::new(Memory::default());
+ let slow = Arc::new(Slow {
+ inner: mem.clone(),
+ delay: std::time::Duration::ZERO,
+ calls: Default::default(),
+ });
+ let v = Arc::new(Vault::new(
+ Box::new(slow.clone()),
+ "MDM-test-unit",
+ "aaaa0012",
+ true,
+ false,
+ ));
+ with_vault(&v, || {
+ let _ = on_disk(&sample());
+ v.run_once();
+ let saved = on_disk(&sample());
+ assert!(saved.contains(REF));
+ let before = slow.calls.load(Ordering::SeqCst);
+ let checked: Settings = prepared(|| serde_json::from_str(&saved).unwrap());
+ assert_eq!(slow.calls.load(Ordering::SeqCst), before);
+ // As on the disk: the references themselves.
+ assert!(checked.proxy_pass.starts_with(REF));
+ });
+ }
+
/// Everything the log gets while secrets go every way: none of them.
#[test]
fn no_secret_reaches_the_log() {
diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs
index 4cb21c3b..697cffa1 100644
--- a/crates/app/src/settings.rs
+++ b/crates/app/src/settings.rs
@@ -1193,6 +1193,10 @@ pub(crate) mod sealed {
}
pub(crate) fn open(stored: &str) -> String {
+ // Read as the disk has it (store::keep_generations only checks that a list reads).
+ if crate::secrets::is_prepared() {
+ return stored.to_owned();
+ }
if stored.starts_with(REF) {
return crate::secrets::vault().open(stored);
}
diff --git a/crates/app/src/store.rs b/crates/app/src/store.rs
index c0053792..dae35f19 100644
--- a/crates/app/src/store.rs
+++ b/crates/app/src/store.rs
@@ -194,7 +194,9 @@ fn keep_generations(p: &Path) {
let Ok(current) = std::fs::read(p) else {
return;
};
- if parse_bytes(&current).is_none() {
+ // Read as it is on the disk: its keychain references aren't opened (secrets.rs), which
+ // would ask the keychain on every save, and on the window's thread at the last one.
+ if crate::secrets::prepared(|| parse_bytes(&current)).is_none() {
return;
}
let _ = std::fs::write(backup_path(p), &current);
diff --git a/crates/app/src/unix.rs b/crates/app/src/unix.rs
index 5ad5d1eb..e829d49d 100644
--- a/crates/app/src/unix.rs
+++ b/crates/app/src/unix.rs
@@ -866,49 +866,34 @@ fn accent_parts(parts: &[f64]) -> Option<egui::Color32> {
/// no value is the default (multicolour: blue). Mapped to Apple's published system colours.
///
/// The Native theme asks every 2 s, from the window's thread, so `defaults` runs on a thread of
-/// its own (#222) and this answers what it said last, one check late; only the first answer is
-/// waited for, at most half a second, so Native starts in the right colour.
+/// its own (#222, crate::launch::Asked) and this answers what it said last, one check late; only
+/// the first answer is waited for, at most half a second, so Native starts in the right colour.
#[cfg(target_os = "macos")]
pub fn mac_accent() -> Option<egui::Color32> {
- use std::sync::Mutex;
- use std::sync::atomic::{AtomicBool, Ordering};
- use std::time::{Duration, Instant};
- /// What `defaults` said last (None: not yet; Some(None): it couldn't be asked).
- static SAID: Mutex<Option<Option<egui::Color32>>> = Mutex::new(None);
- static ASKING: AtomicBool = AtomicBool::new(false);
- let said = || *SAID.lock().unwrap_or_else(|e| e.into_inner());
- if !ASKING.swap(true, Ordering::AcqRel) {
- let asked = std::thread::Builder::new()
- .name("mac-accent".into())
- .spawn(|| {
- let out = crate::launch::output_within(
- Command::new("defaults").args(["read", "-g", "AppleAccentColor"]),
- Duration::from_secs(2),
- );
- let color = out.map(|out| {
- let n = String::from_utf8_lossy(&out.stdout)
- .trim()
- .parse::<i32>()
- .ok();
- mac_accent_color(n)
- });
- *SAID.lock().unwrap_or_else(|e| e.into_inner()) = Some(color);
- ASKING.store(false, Ordering::Release);
- });
- if asked.is_err() {
- ASKING.store(false, Ordering::Release);
- }
- }
- let start = Instant::now();
- loop {
- if let Some(color) = said() {
- return color;
- }
- if start.elapsed() > Duration::from_millis(500) {
- return None;
- }
- std::thread::sleep(Duration::from_millis(10));
- }
+ use std::time::Duration;
+ /// What `defaults` said last (None inside: it couldn't be asked).
+ static SAID: std::sync::LazyLock<crate::launch::Asked<(), Option<egui::Color32>>> =
+ std::sync::LazyLock::new(Default::default);
+ SAID.get(
+ &(),
+ Duration::ZERO,
+ Duration::from_millis(500),
+ None,
+ |_| {
+ let out = crate::launch::output_within(
+ Command::new("defaults").args(["read", "-g", "AppleAccentColor"]),
+ Duration::from_secs(2),
+ );
+ out.map(|out| {
+ let n = String::from_utf8_lossy(&out.stdout)
+ .trim()
+ .parse::<i32>()
+ .ok();
+ mac_accent_color(n)
+ })
+ },
+ )
+ .flatten()
}
/// AppleAccentColor's number (None: not set) as the colour it stands for.
@@ -968,15 +953,31 @@ pub fn on_wayland() -> bool {
/// Linux: a tray host is there to show MDM's icon (a StatusNotifierWatcher on the session bus:
/// KDE, waybar's tray, GNOME's AppIndicator extension), #59. Without one (MangoWC, plain
/// window managers), closing the window would hide it where nothing can bring it back.
+///
+/// The window asks every frame, so the bus is asked on a thread of its own at most every 2 s
+/// (crate::launch::Asked) and this answers what it said last; only the first answer is waited
+/// for, at most a quarter of a second. A bus that doesn't answer reads as no tray host.
#[cfg(target_os = "linux")]
pub fn tray_host() -> bool {
+ static ASKED: std::sync::LazyLock<crate::launch::Asked<(), bool>> =
+ std::sync::LazyLock::new(Default::default);
let has = || -> zbus::Result<bool> {
- let bus = zbus::blocking::Connection::session()?;
+ let bus = zbus::blocking::connection::Builder::session()?
+ .method_timeout(std::time::Duration::from_secs(5))
+ .build()?;
let dbus = zbus::blocking::fdo::DBusProxy::new(&bus)?;
let name = zbus::names::BusName::try_from("org.kde.StatusNotifierWatcher")?;
Ok(dbus.name_has_owner(name)?)
};
- has().unwrap_or(false)
+ ASKED
+ .get(
+ &(),
+ std::time::Duration::from_secs(2),
+ std::time::Duration::from_millis(250),
+ None,
+ move |_| has().unwrap_or(false),
+ )
+ .unwrap_or(false)
}
/// `win32::on_a_screen`: winit has no monitor list before the window exists, so a saved
@@ -2106,7 +2107,9 @@ pub fn wake_at(at: Option<i64>) -> Result<(), String> {
/// Keep the computer from sleeping while `reason` is given; None lets it sleep again as the
/// system's settings say. Linux: logind's sleep and idle inhibitor, held by its file
/// descriptor (`systemd-inhibit --list` shows it with its reason); a user in the active
-/// session may take it without a password. False when logind refused.
+/// session may take it without a password. False when logind refused, or didn't answer within
+/// 25 s. Called on wake::Holder's thread, never the window's: logind can be slow right after a
+/// resume.
#[cfg(target_os = "linux")]
pub fn keep_awake(reason: Option<&str>) -> bool {
use std::sync::Mutex;
@@ -2118,7 +2121,9 @@ pub fn keep_awake(reason: Option<&str>) -> bool {
return true;
};
let take = || -> zbus::Result<zbus::zvariant::OwnedFd> {
- let conn = zbus::blocking::Connection::system()?;
+ let conn = zbus::blocking::connection::Builder::system()?
+ .method_timeout(std::time::Duration::from_secs(25))
+ .build()?;
let logind = zbus::blocking::Proxy::new(
&conn,
"org.freedesktop.login1",
diff --git a/crates/app/src/wake.rs b/crates/app/src/wake.rs
index 55c14e0d..eccfb561 100644
--- a/crates/app/src/wake.rs
+++ b/crates/app/src/wake.rs
@@ -18,6 +18,8 @@
//! sleep settings apply again, and the queue's "Turn off computer when done" can put it to
//! sleep at once.
+use std::sync::mpsc::{Receiver, Sender};
+
use chrono::{DateTime, Datelike, Duration, Local, NaiveDateTime, TimeZone, Utc};
use crate::queue::{Queue, Schedule};
@@ -184,6 +186,8 @@ pub struct Waker {
/// When keeping the computer awake was last refused, and how often in a row (asked again
/// 5 s later, after a minute of refusals once a minute).
refused: Option<(std::time::Instant, u32)>,
+ /// The system's keep-awake, asked on a thread of its own.
+ holder: Holder,
}
impl Waker {
@@ -246,20 +250,36 @@ impl Waker {
}
}
- /// Keep the computer awake while `on` (a queue with the option is running).
+ /// Keep the computer awake while `on` (a queue with the option is running). Returns at once:
+ /// the system is asked on the holder's thread, and its answer read on a later call.
pub fn keep_awake(&mut self, on: bool, queue: &str) {
if !on {
self.refused = None;
if std::mem::take(&mut self.awake) {
tracing::info!("wake: no longer keeping the computer awake");
- hold_awake(None);
+ }
+ // A hold still on its way is let go once it is taken (the thread asks in turn).
+ if self.holder.may_hold() {
+ self.holder.release();
}
return;
}
+ if let Some(held) = self.holder.answer() {
+ if held {
+ tracing::info!("wake: keeping the computer awake");
+ self.awake = true;
+ self.refused = None;
+ } else {
+ self.refusal();
+ }
+ }
// A refusal is asked again a little later: logind refuses while the sleep the computer
// just woke from is still ending, which is when a woken queue starts.
let wait = |n: u32| std::time::Duration::from_secs(if n < 12 { 5 } else { 60 });
- if self.awake || self.refused.is_some_and(|(t, n)| t.elapsed() < wait(n)) {
+ if self.awake
+ || self.holder.asking()
+ || self.refused.is_some_and(|(t, n)| t.elapsed() < wait(n))
+ {
return;
}
let reason = crate::i18n::fmt(
@@ -267,25 +287,177 @@ impl Waker {
crate::i18n::t("Mister Download Manager is running the queue \"{queue}\""),
&[("queue", crate::i18n::t(queue))],
);
- if hold_awake(Some(&reason)) {
- tracing::info!("wake: keeping the computer awake");
- self.awake = true;
- self.refused = None;
- } else {
- let n = self.refused.map_or(0, |(_, n)| n);
- self.refused = Some((std::time::Instant::now(), n + 1));
+ if !self.holder.hold(reason) {
+ self.refusal();
}
}
- /// Cancel the wake (MDM is quitting: Linux's alarm would outlive it).
+ fn refusal(&mut self) {
+ let n = self.refused.map_or(0, |(_, n)| n);
+ self.refused = Some((std::time::Instant::now(), n + 1));
+ }
+
+ /// Cancel the wake (MDM is quitting: Linux's alarm would outlive it). The computer may sleep
+ /// again: waited for at most a second (the system lets go of it when MDM ends anyway).
pub fn clear(&mut self) {
self.wanted = None;
if std::mem::take(&mut self.armed) {
let _ = arm(None);
}
- if self.awake {
- self.awake = false;
- hold_awake(None);
+ self.awake = false;
+ if self.holder.may_hold() {
+ self.holder
+ .release_within(std::time::Duration::from_secs(1));
+ }
+ }
+}
+
+/// An order for the holder's thread, with its number.
+enum Order {
+ /// Keep the computer awake for this reason; answered with whether the system agreed.
+ Hold(u64, String),
+ /// Let it sleep again; answered once done.
+ Release(u64),
+}
+
+/// The system's call: keep the computer awake for a reason, or let it sleep (None); false when
+/// the system refused.
+type Call = Box<dyn FnMut(Option<&str>) -> bool + Send>;
+
+/// The holder's thread: the orders to it, and its answers (the order's number, the system's).
+struct HolderThread {
+ orders: Sender<Order>,
+ answers: Receiver<(u64, bool)>,
+}
+
+/// The system's keep-awake (Windows' power request, logind's inhibitor, `caffeinate`), asked on a
+/// thread of its own: logind can be slow to answer right after a resume, which is exactly when a
+/// woken queue starts (and it is asked again every 5 s while it refuses), so the window never
+/// waits for it. The thread takes the orders in turn: a release sent while a hold is still on
+/// its way lets go of that hold.
+struct Holder {
+ /// Taken by the thread when it starts.
+ call: Option<Call>,
+ thread: Option<HolderThread>,
+ /// The hold waiting for its answer.
+ asked: Option<u64>,
+ /// The system agreed to the last hold, and it wasn't released since.
+ held: bool,
+ next: u64,
+}
+
+impl Default for Holder {
+ fn default() -> Self {
+ Holder::new(Box::new(hold_awake))
+ }
+}
+
+impl Holder {
+ fn new(call: Call) -> Holder {
+ Holder {
+ call: Some(call),
+ thread: None,
+ asked: None,
+ held: false,
+ next: 0,
+ }
+ }
+
+ /// Hand the order made with the next number to the thread, starting it the first time: that
+ /// number, or None when there is no thread to take it.
+ fn send(&mut self, order: impl FnOnce(u64) -> Order) -> Option<u64> {
+ if self.thread.is_none() {
+ let mut call = self.call.take()?;
+ let (tx, orders) = std::sync::mpsc::channel::<Order>();
+ let (answers, rx) = std::sync::mpsc::channel();
+ let started = std::thread::Builder::new()
+ .name("keep-awake".into())
+ .spawn(move || {
+ for order in orders {
+ let answer = match order {
+ Order::Hold(n, reason) => (n, call(Some(&reason))),
+ Order::Release(n) => (n, call(None)),
+ };
+ if answers.send(answer).is_err() {
+ break;
+ }
+ }
+ });
+ if let Err(e) = started {
+ tracing::warn!("wake: no thread to keep the computer awake on: {e}");
+ return None;
+ }
+ self.thread = Some(HolderThread {
+ orders: tx,
+ answers: rx,
+ });
+ }
+ self.next += 1;
+ let n = self.next;
+ let thread = self.thread.as_ref()?;
+ thread.orders.send(order(n)).ok().map(|()| n)
+ }
+
+ /// Ask for the computer to be kept awake; false when it can't be asked at all.
+ fn hold(&mut self, reason: String) -> bool {
+ self.asked = self.send(|n| Order::Hold(n, reason));
+ self.asked.is_some()
+ }
+
+ /// A hold is on its way, not answered yet.
+ fn asking(&self) -> bool {
+ self.asked.is_some()
+ }
+
+ /// The computer may be kept awake now, or soon: a hold held, or still on its way.
+ fn may_hold(&self) -> bool {
+ self.held || self.asked.is_some()
+ }
+
+ /// The hold's answer, once it has come (true: held).
+ fn answer(&mut self) -> Option<bool> {
+ let asked = self.asked?;
+ let thread = self.thread.as_ref()?;
+ while let Ok((n, held)) = thread.answers.try_recv() {
+ if n == asked {
+ self.asked = None;
+ self.held = held;
+ return Some(held);
+ }
+ }
+ None
+ }
+
+ /// Let the computer sleep again (after any hold still on its way): the order's number.
+ fn release(&mut self) -> Option<u64> {
+ self.asked = None;
+ self.held = false;
+ self.send(Order::Release)
+ }
+
+ /// [`Holder::release`], waiting at most `limit` for it to be done: whether it was.
+ fn release_within(&mut self, limit: std::time::Duration) -> bool {
+ let Some(n) = self.release() else {
+ return false;
+ };
+ let Some(thread) = self.thread.as_ref() else {
+ return false;
+ };
+ let start = std::time::Instant::now();
+ loop {
+ match thread
+ .answers
+ .recv_timeout(limit.saturating_sub(start.elapsed()))
+ {
+ Ok((m, _)) if m == n => return true,
+ Ok(_) => {}
+ Err(_) => {
+ tracing::warn!(
+ "wake: the system hasn't answered within {limit:?}; MDM's hold ends with it"
+ );
+ return false;
+ }
+ }
}
}
}
@@ -414,6 +586,139 @@ mod tests {
assert_eq!(next_wake(&queues[..1], now), None);
}
+ use std::sync::{Arc, Mutex};
+ use std::time::Instant;
+
+ /// The queue's name (a constant: a literal in a call would be taken for a text to translate).
+ const QUEUE: &str = "night";
+
+ /// What a fake system was asked: a reason (hold) or None (let go).
+ type Asked = Arc<Mutex<Vec<Option<String>>>>;
+
+ /// A Waker whose system takes `slow` to answer each hold, and answers `agrees`.
+ fn waker(slow: std::time::Duration, agrees: bool) -> (Waker, Asked) {
+ let asked = Asked::default();
+ let log = asked.clone();
+ let call: Call = Box::new(move |reason| {
+ log.lock().unwrap().push(reason.map(str::to_owned));
+ if reason.is_some() {
+ std::thread::sleep(slow);
+ agrees
+ } else {
+ true
+ }
+ });
+ let w = Waker {
+ holder: Holder::new(call),
+ ..Waker::default()
+ };
+ // The translations are read once, on the first text (the app has read them long before).
+ let _ = crate::i18n::t("Mister Download Manager is running the queue \"{queue}\"");
+ (w, asked)
+ }
+
+ /// Call `keep_awake` as the window does, each call timed, until `done` or `limit`.
+ fn ticks(w: &mut Waker, on: bool, limit: std::time::Duration, done: impl Fn(&Waker) -> bool) {
+ let start = Instant::now();
+ while !done(w) && start.elapsed() < limit {
+ let t = Instant::now();
+ w.keep_awake(on, QUEUE);
+ assert!(
+ t.elapsed() < std::time::Duration::from_millis(50),
+ "keep_awake waited {:?}",
+ t.elapsed()
+ );
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ }
+
+ #[test]
+ fn keeping_awake_never_waits_for_a_slow_system() {
+ let secs = std::time::Duration::from_secs;
+ let (mut w, asked) = waker(secs(2), true);
+ let t = Instant::now();
+ w.keep_awake(true, QUEUE);
+ assert!(t.elapsed() < std::time::Duration::from_millis(50));
+ assert!(!w.awake, "not held before the system said so");
+ // Every tick returns at once while the system takes its time, and it is asked once.
+ ticks(&mut w, true, secs(6), |w| w.awake);
+ assert!(w.awake, "held once the system agreed");
+ assert_eq!(asked.lock().unwrap().len(), 1);
+ assert!(asked.lock().unwrap()[0].as_deref().unwrap().contains(QUEUE));
+ // The queue stops: let go, at once too.
+ let t = Instant::now();
+ w.keep_awake(false, "");
+ assert!(t.elapsed() < std::time::Duration::from_millis(50));
+ assert!(!w.awake);
+ let start = Instant::now();
+ while asked.lock().unwrap().len() < 2 && start.elapsed() < secs(3) {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ assert_eq!(asked.lock().unwrap()[1], None, "let go");
+ }
+
+ #[test]
+ fn a_refusal_is_asked_again_later_not_every_tick() {
+ let secs = std::time::Duration::from_secs;
+ let (mut w, asked) = waker(std::time::Duration::ZERO, false);
+ ticks(&mut w, true, secs(2), |w| w.refused.is_some());
+ assert_eq!(w.refused.map(|(_, n)| n), Some(1));
+ // The next ticks within the 5 s don't ask again.
+ ticks(&mut w, true, std::time::Duration::from_millis(200), |_| {
+ false
+ });
+ assert_eq!(asked.lock().unwrap().len(), 1);
+ // 5 s later it is asked again.
+ let earlier = Instant::now().checked_sub(secs(6)).unwrap();
+ w.refused = Some((earlier, 1));
+ ticks(&mut w, true, secs(2), |w| {
+ w.refused.is_some_and(|(_, n)| n == 2)
+ });
+ assert_eq!(asked.lock().unwrap().len(), 2);
+ assert!(!w.awake);
+ // Nothing held: nothing to let go.
+ w.keep_awake(false, "");
+ assert_eq!(w.refused, None);
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ assert_eq!(asked.lock().unwrap().len(), 2);
+ }
+
+ #[test]
+ fn stopping_while_the_hold_is_on_its_way_lets_it_go() {
+ let (mut w, asked) = waker(std::time::Duration::from_millis(300), true);
+ w.keep_awake(true, QUEUE);
+ w.keep_awake(false, "");
+ let start = Instant::now();
+ while asked.lock().unwrap().len() < 2 && start.elapsed() < std::time::Duration::from_secs(3)
+ {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ let asked = asked.lock().unwrap().clone();
+ assert!(asked[0].is_some() && asked[1].is_none(), "{asked:?}");
+ // The late "yes" is never taken for the stopped queue's.
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ w.keep_awake(false, "");
+ assert!(!w.awake);
+ }
+
+ #[test]
+ fn quitting_waits_for_a_hanging_system_at_most_a_second() {
+ let (mut w, asked) = waker(std::time::Duration::from_secs(10), true);
+ w.keep_awake(true, QUEUE);
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ let t = Instant::now();
+ w.clear();
+ let took = t.elapsed();
+ assert!(took < std::time::Duration::from_millis(1500), "{took:?}");
+ assert!(!w.awake);
+ assert_eq!(asked.lock().unwrap().len(), 1);
+ // A system that answers: quitting lets go, and waits for it.
+ let (mut w, asked) = waker(std::time::Duration::ZERO, true);
+ ticks(&mut w, true, std::time::Duration::from_secs(2), |w| w.awake);
+ w.clear();
+ assert_eq!(asked.lock().unwrap().last(), Some(&None));
+ }
+
#[test]
fn a_local_time_has_a_utc_time() {
let local = at(2026, 11, 6, 23, 0, 0);