Skip to content

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

Theme: Windows' light or dark and the theme files read beside the window (#719) (#735)

Ahmed Nefzaoui4d1e47cadf0e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 302233fc..cd9fbc99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- Windows: the window no longer freezes while it checks whether Windows is in light or dark mode. Every 2 seconds the window read Windows' app mode (and, with the **Native** theme, its accent and contrast colours) from the registry, and looked at the themes folder and pywal's colours on the disk, on its own thread; where the registry took seconds to answer, the window waited that long ("freeze in misterdownloadmanager::theme::update"). A thread beside the window now reads them, at once when Windows says one of those settings changed, and the window shows its last answer without waiting: switching Windows between light and dark, a new accent, a theme file added to the themes folder and pywal's new colours are followed as before ([#719](https://github.com/anefzaoui/misterdownloadmanager/issues/719)).
- Wikimedia Commons videos download again: their quality list carries a negative size estimate, which MDM took for a page with no video at all ("it gave no video information"), and so did one yt-dlp says is neither a plain file nor not (`"direct": null`).
- The Download video button no longer comes back when you play or pause the video: only moving the pointer over it shows it. It fades 1.5 seconds after the pointer stops (2.6 before), and at once when the pointer leaves the video (part of [#741](https://github.com/anefzaoui/misterdownloadmanager/issues/741)).
- Windows 10: the download's progress window no longer shows a black band above its title bar, with its contents moved down and every click landing above the button it showed (you had to click above a button for it to work); the same goes for the dialogs with a Metro, Luna, Aero or Aqua title bar. These windows kept the system's title bar style underneath MDM's own, hidden, and the picture was placed where that hidden title bar would have ended, as it was on a Windows 11 Insider build, fixed there in 0.5.0 ([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208)). They are now framed on Windows 10 as on Windows 11, with no title bar style at all, and a thin border round them ([#620](https://github.com/anefzaoui/misterdownloadmanager/issues/620)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 21a1be2d..b2748169 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -577,6 +577,9 @@ These ship in a later version, when they're ready.
### Being built
+- πŸ”„ A freeze of the window while it checked Windows' light or dark mode: the registry took
+ seconds to answer ([#719](https://github.com/anefzaoui/misterdownloadmanager/issues/719)): the
+ system's look and the theme files are now read beside the window; fix in review
- πŸ”„ Helium: MDM offers it the extension on Linux and macOS, through Helium's own services, the
Linux packages' helper files cover it, and the docs say how to add the extension in Helium
([#685](https://github.com/anefzaoui/misterdownloadmanager/issues/685)); in review
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 0b0a0d40..254b846c 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -1039,11 +1039,10 @@ pub struct App {
zoom: f32,
/// The main window was brought inside the screen after the start (scale::fit_window).
fitted: bool,
- /// View β†’ Theme's choices (#45), and when the themes folder last changed (read again then).
+ /// View β†’ Theme's choices (#45), and the number of the theme watcher's answer they come from
+ /// (`lookwatch::theme_files`: taken again when it changes).
theme_list: Vec<crate::themefile::Entry>,
- themes_changed: Option<std::time::SystemTime>,
- /// pywal's colours were there at the last check (View β†’ Theme β†’ pywal listed then).
- pywal_there: bool,
+ theme_files_seen: u64,
/// When `logic`'s every-2-seconds work last ran (crash state, torrents, #174).
ticked: Option<Instant>,
/// The main window's caption matches the mode.
@@ -1632,9 +1631,9 @@ impl App {
theme_checked: None,
zoom,
fitted: false,
- theme_list: crate::themefile::list(),
- themes_changed: crate::themefile::changed(),
- pywal_there: crate::themefile::pywal_file().is_some_and(|p| p.is_file()),
+ // The built-ins until the watcher's first look at the themes folder (#719).
+ theme_list: crate::themefile::list_in(None, None),
+ theme_files_seen: 0,
ticked: None,
caption_set: false,
// The system's title bar is the frame's own: nothing to apply for it.
@@ -8807,7 +8806,7 @@ impl App {
fn add_theme_file(&mut self, path: &std::path::Path, ctx: &egui::Context) {
match crate::themefile::add(path) {
Ok(id) => {
- self.themes_changed = crate::themefile::changed();
+ // Listed at once (the watcher would at its next look).
self.theme_list = crate::themefile::list();
self.run(Cmd::Theme(crate::chrome::label(&id)), None, ctx);
}
@@ -10206,13 +10205,14 @@ impl App {
{
self.theme_checked = Some(Instant::now());
// A theme file added, removed or renamed, pywal's colours written or taken away:
- // View β†’ Theme lists it.
- let changed = crate::themefile::changed();
- let wal = crate::themefile::pywal_file().is_some_and(|p| p.is_file());
- if changed != self.themes_changed || wal != self.pywal_there {
- self.themes_changed = changed;
- self.pywal_there = wal;
- self.theme_list = crate::themefile::list();
+ // View β†’ Theme lists it. Nothing here reads the registry or the disk: `lookwatch`'s
+ // threads do, and this takes what they found last (#719).
+ let files = crate::lookwatch::theme_files(&ctx);
+ if let Some((seen, found)) = &files
+ && *seen != self.theme_files_seen
+ {
+ self.theme_files_seen = *seen;
+ self.theme_list = found.list.clone();
}
let changed = crate::theme::update(
self.settings.dark_mode_support,
@@ -10221,7 +10221,9 @@ impl App {
);
// Native follows the system's accent and contrast as they change, a theme made from
// pywal's colours the colours `wal` writes for each new wallpaper.
- let changed = if crate::theme::follow_system(&ctx) || crate::theme::follow_pywal() {
+ let changed = if crate::theme::follow_system(&ctx)
+ || crate::theme::follow_pywal(files.as_ref().map(|(_, f)| f))
+ {
crate::theme::apply_theme(&ctx);
true
} else {
diff --git a/crates/app/src/lookwatch.rs b/crates/app/src/lookwatch.rs
new file mode 100644
index 00000000..c57435be
--- /dev/null
+++ b/crates/app/src/lookwatch.rs
@@ -0,0 +1,419 @@
+//! What the look follows outside MDM, read off the window's thread (#719): Windows' light or dark
+//! app mode, its accent and contrast colours (the registry), and the theme files (the data
+//! folder's `themes` folder, pywal's colours). A registry read can wait for seconds (#719: 8 s,
+//! on the window's thread, froze the window), a folder on a slow or network disk as long; so a
+//! thread of their own reads each ([`Watched`]), the window takes the last answer and is woken
+//! when one changes. The rule of the clipboard's reads (#418) and the torrents' numbers (#693).
+//!
+//! Linux's desktop settings come from the portal's and the theme settings' own threads
+//! (`unix::desktop_dark`), macOS's accent from `launch::Asked`; neither is read here.
+
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
+use std::time::{Duration, Instant};
+
+use crate::palette::Theme;
+use crate::themefile::{self, Entry, Followed, Stamp};
+
+/// How often each source is read again when nothing said it changed: the theme check's 2 s.
+const EVERY: Duration = Duration::from_secs(2);
+
+/// The longest the window waits for the system's first answer, once (as it starts): enough for a
+/// registry that answers, so the window opens in the right mode; a light one until it comes.
+#[cfg_attr(not(windows), allow(dead_code))]
+const FIRST_WAIT: Duration = Duration::from_millis(500);
+
+/// A value read again and again by a thread of its own: the window asks for the last answer
+/// ([`Watched::latest`]), which never waits for a read, and is told when one changes. A read that
+/// never returns holds up nothing but the next read.
+pub struct Watched<T> {
+ shared: Arc<Shared<T>>,
+}
+
+struct Shared<T> {
+ state: Mutex<State<T>>,
+ came: Condvar,
+}
+
+struct State<T> {
+ /// The last answer, and how many different answers came (its number).
+ latest: Option<T>,
+ generation: u64,
+ closed: bool,
+}
+
+impl<T> Shared<T> {
+ fn lock(&self) -> MutexGuard<'_, State<T>> {
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+}
+
+impl<T: Clone + PartialEq + Send + 'static> Watched<T> {
+ /// `read` reads the source (it may wait, for ever); `wait` returns when it should be read
+ /// again (a change notified, or its time); `wake` is told when an answer differs from the
+ /// last one.
+ pub fn new(
+ name: &str,
+ mut read: impl FnMut() -> T + Send + 'static,
+ mut wait: impl FnMut() + Send + 'static,
+ wake: impl Fn() + Send + 'static,
+ ) -> Self {
+ let shared = Arc::new(Shared {
+ state: Mutex::new(State {
+ latest: None,
+ generation: 0,
+ closed: false,
+ }),
+ came: Condvar::new(),
+ });
+ let worker = shared.clone();
+ let spawned = std::thread::Builder::new()
+ .name(name.into())
+ .spawn(move || {
+ loop {
+ // Not under the lock: the window never waits for a read.
+ let value = read();
+ let changed = {
+ let mut s = worker.lock();
+ if s.closed {
+ return;
+ }
+ let changed = s.latest.as_ref() != Some(&value);
+ if changed {
+ s.latest = Some(value);
+ s.generation += 1;
+ worker.came.notify_all();
+ }
+ changed
+ };
+ if changed {
+ wake();
+ }
+ wait();
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!("{name}: no thread to read it ({e}), not followed");
+ }
+ Watched { shared }
+ }
+
+ /// The last answer and its number (1 for the first, one more for each change); None before
+ /// the first. Never waits for a read.
+ pub fn latest(&self) -> Option<(u64, T)> {
+ let s = self.shared.lock();
+ s.latest.clone().map(|v| (s.generation, v))
+ }
+
+ /// [`Watched::latest`], waiting at most `within` for the first answer.
+ // Windows' system look only: Linux's and macOS's come from their own watchers.
+ #[cfg_attr(not(windows), allow(dead_code))]
+ pub fn first(&self, within: Duration) -> Option<(u64, T)> {
+ let start = Instant::now();
+ let mut s = self.shared.lock();
+ while s.latest.is_none() {
+ let left = within.saturating_sub(start.elapsed());
+ if left.is_zero() {
+ return None;
+ }
+ s = self
+ .shared
+ .came
+ .wait_timeout(s, left)
+ .unwrap_or_else(PoisonError::into_inner)
+ .0;
+ }
+ s.latest.clone().map(|v| (s.generation, v))
+ }
+
+ /// How many different answers came.
+ pub fn generation(&self) -> u64 {
+ self.shared.lock().generation
+ }
+}
+
+impl<T> Drop for Watched<T> {
+ fn drop(&mut self) {
+ self.shared.lock().closed = true;
+ }
+}
+
+/// The window woken when an answer changes (set at the first ask).
+static WINDOW: OnceLock<egui::Context> = OnceLock::new();
+
+fn window(ctx: &egui::Context) {
+ let _ = WINDOW.set(ctx.clone());
+}
+
+fn wake_window() {
+ if let Some(ctx) = WINDOW.get() {
+ ctx.request_repaint();
+ }
+}
+
+/// How many times what the watchers here read changed: the app's theme check runs in the frame
+/// such a change wakes (`theme::system_changed`), not at its next 2 s.
+pub fn generation() -> u64 {
+ #[cfg(windows)]
+ let system = SYSTEM.get().map_or(0, Watched::generation);
+ #[cfg(not(windows))]
+ let system = 0;
+ system + FILES.get().map_or(0, Watched::generation)
+}
+
+// ---- Windows' app mode and colours -----------------------------------------------------------
+
+/// What Windows says about the look: dark apps, and the accent and contrast colours (Native).
+#[cfg(windows)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct SystemLook {
+ pub dark: bool,
+ pub native: crate::native::System,
+}
+
+#[cfg(windows)]
+static SYSTEM: OnceLock<Watched<SystemLook>> = OnceLock::new();
+
+/// What Windows said last: read again at once when the registry says one of its keys changed
+/// (`win32::LookKeys`), else every 2 s. Waits only at the very first ask, at most
+/// [`FIRST_WAIT`]; light with no accent until an answer comes.
+#[cfg(windows)]
+pub fn system(ctx: &egui::Context) -> SystemLook {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ static ASKED: AtomicBool = AtomicBool::new(false);
+ window(ctx);
+ let watched = SYSTEM.get_or_init(|| {
+ // The keys are opened by the watcher's thread too: opening one can wait as a read does.
+ let mut keys: Option<crate::win32::LookKeys> = None;
+ Watched::new(
+ "system look",
+ || SystemLook {
+ dark: crate::win32::apps_use_dark(),
+ native: crate::native::windows_now(),
+ },
+ move || {
+ keys.get_or_insert_with(crate::win32::LookKeys::open)
+ .wait(EVERY)
+ },
+ wake_window,
+ )
+ });
+ let within = if ASKED.swap(true, Ordering::Relaxed) {
+ Duration::ZERO
+ } else {
+ FIRST_WAIT
+ };
+ watched.first(within).map(|(_, v)| v).unwrap_or_default()
+}
+
+// ---- the theme files ---------------------------------------------------------------------------
+
+/// The theme files as the watcher last found them.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct ThemeFiles {
+ /// View β†’ Theme's themes ([`themefile::list`]).
+ pub list: Vec<Entry>,
+ /// The active theme read again after `wal` wrote pywal's file anew (the last time it did).
+ pub pywal: Option<PywalRead>,
+}
+
+/// The active theme read again from pywal's rewritten file.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PywalRead {
+ /// The theme (its id or path, as chosen) and the file it followed, as they were then: the
+ /// window takes it only while they still are.
+ pub id: String,
+ pub followed: Followed,
+ /// The file's stamp that was new.
+ pub written: Stamp,
+ /// The theme and what in it was skipped, or why it didn't read; and the file to follow now.
+ pub read: Result<(Theme, Vec<String>), String>,
+ pub follow: Option<Followed>,
+}
+
+static FILES: OnceLock<Watched<ThemeFiles>> = OnceLock::new();
+
+/// The theme files as the watcher last found them, with their number (it changes with them);
+/// None before its first look. Never waits.
+pub fn theme_files(ctx: &egui::Context) -> Option<(u64, ThemeFiles)> {
+ window(ctx);
+ FILES
+ .get_or_init(|| {
+ Watched::new(
+ "theme files",
+ files_reader(|| (themefile::dir(), themefile::pywal_file())),
+ || std::thread::sleep(EVERY),
+ wake_window,
+ )
+ })
+ .latest()
+}
+
+/// A reader of the themes folder and pywal's file, which `places` names (asked on the reader's
+/// thread: finding them can look at the disk). The folder is listed again when its time or
+/// pywal's file changed (a file added, removed or renamed; `wal` run for the first time or its
+/// colours removed); the active theme is read again when it follows pywal's file and `wal`
+/// wrote it since ([`themefile::following_pywal`]).
+fn files_reader(
+ places: impl FnOnce() -> (Option<PathBuf>, Option<PathBuf>) + Send + 'static,
+) -> impl FnMut() -> ThemeFiles + Send + 'static {
+ let mut places = Some(places);
+ let mut found: Option<(Option<PathBuf>, Option<PathBuf>)> = None;
+ let mut seen = None;
+ let mut files = ThemeFiles::default();
+ let mut reread: Option<(Followed, Stamp, String)> = None;
+ move || {
+ if found.is_none() {
+ found = places.take().map(|f| f());
+ }
+ let (dir, wal) = found.clone().unwrap_or_default();
+ let now = (
+ dir.as_deref().and_then(themefile::folder_stamp),
+ wal.as_deref().is_some_and(Path::is_file),
+ );
+ if seen != Some(now) {
+ seen = Some(now);
+ files.list = themefile::list_in(dir.as_deref(), wal);
+ }
+ if let Some(followed) = themefile::following_pywal() {
+ let written = themefile::stamp(&followed.0);
+ let id = crate::theme::selected();
+ let key = (followed.clone(), written, id.clone());
+ // Once for each write: the window takes it in the frame it wakes.
+ if written != followed.1 && reread.as_ref() != Some(&key) {
+ reread = Some(key);
+ let (read, follow) = themefile::read(&id);
+ files.pywal = Some(PywalRead {
+ id,
+ followed,
+ written,
+ read: read.map(|l| (l.theme, l.warnings)),
+ follow,
+ });
+ }
+ }
+ files.clone()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::mpsc;
+
+ /// A source that answers once, then never again (a registry read or a folder that hangs, as
+ /// in #719): the window's asks still answer at once, with the last answer.
+ #[test]
+ fn a_read_that_never_returns_holds_up_nothing() {
+ let (woke_tx, woke_rx) = mpsc::channel();
+ let (_hold, never) = mpsc::channel::<()>();
+ let reads = Arc::new(AtomicUsize::new(0));
+ let counted = reads.clone();
+ let w = Watched::new(
+ "test hang",
+ move || {
+ if counted.fetch_add(1, Ordering::SeqCst) > 0 {
+ // Hangs for good: nothing is ever sent.
+ let _ = never.recv();
+ }
+ true
+ },
+ || {},
+ move || {
+ let _ = woke_tx.send(());
+ },
+ );
+ // The first answer came, and woke the window.
+ woke_rx.recv_timeout(Duration::from_secs(5)).unwrap();
+ assert_eq!(w.first(Duration::from_secs(5)), Some((1, true)));
+ // The second read hangs. Every frame's ask answers at once all the same.
+ while reads.load(Ordering::SeqCst) < 2 {
+ std::thread::yield_now();
+ }
+ let start = Instant::now();
+ for _ in 0..1000 {
+ assert_eq!(w.latest(), Some((1, true)));
+ assert_eq!(w.generation(), 1);
+ }
+ assert!(start.elapsed() < Duration::from_millis(500));
+ }
+
+ /// A source that hangs from its very first read: the window gets no answer (the defaults),
+ /// at once, or after the bounded first wait.
+ #[test]
+ fn a_first_read_that_never_returns_holds_up_nothing() {
+ let (_hold, never) = mpsc::channel::<()>();
+ let w: Watched<bool> = Watched::new(
+ "test hang first",
+ move || {
+ let _ = never.recv();
+ true
+ },
+ || {},
+ || {},
+ );
+ let start = Instant::now();
+ assert_eq!(w.latest(), None);
+ assert_eq!(w.first(Duration::from_millis(100)), None);
+ assert!(start.elapsed() < Duration::from_secs(2));
+ }
+
+ /// Only a different answer counts as a change, and wakes the window.
+ #[test]
+ fn changes_are_counted_and_wake() {
+ let (tx, rx) = mpsc::channel::<u32>();
+ let (woke_tx, woke_rx) = mpsc::channel();
+ let rx = Mutex::new(rx);
+ let w = Watched::new(
+ "test changes",
+ move || rx.lock().unwrap().recv().unwrap_or(0),
+ || {},
+ move || {
+ let _ = woke_tx.send(());
+ },
+ );
+ for v in [1, 1, 1, 2] {
+ tx.send(v).unwrap();
+ }
+ woke_rx.recv_timeout(Duration::from_secs(5)).unwrap();
+ woke_rx.recv_timeout(Duration::from_secs(5)).unwrap();
+ assert_eq!(w.latest(), Some((2, 2)));
+ assert!(woke_rx.recv_timeout(Duration::from_millis(100)).is_err());
+ drop(tx);
+ }
+
+ /// The reader lists a theme added to the folder at its next look, and pywal's colours once
+ /// `wal` writes them; a folder that didn't change isn't listed again.
+ #[test]
+ fn the_files_reader_sees_a_theme_added() {
+ let dir = std::env::temp_dir().join(format!("mdm-lookwatch-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let themes = dir.join("themes");
+ std::fs::create_dir_all(&themes).unwrap();
+ let wal = dir.join("wal").join("colors.json");
+ let mut read = files_reader({
+ let (themes, wal) = (themes.clone(), wal.clone());
+ move || (Some(themes), Some(wal))
+ });
+ let builtins = read().list;
+ assert!(builtins.iter().all(|e| e.path.is_none()));
+ std::fs::write(themes.join("sunny.toml"), "name = \"Sunny\"\n").unwrap();
+ // A folder's time can be coarse: written until the folder says it changed.
+ let start = Instant::now();
+ let list = loop {
+ let list = read().list;
+ if list.len() > builtins.len() || start.elapsed() > Duration::from_secs(5) {
+ break list;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ std::fs::write(themes.join("touch.txt"), "").unwrap();
+ };
+ let sunny = list.iter().find(|e| e.id == "sunny").expect("listed");
+ assert_eq!(sunny.name, "Sunny");
+ std::fs::create_dir_all(wal.parent().unwrap()).unwrap();
+ std::fs::write(&wal, "{}").unwrap();
+ assert!(read().list.iter().any(|e| e.id == themefile::PYWAL));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index bd2ec723..33491383 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -31,6 +31,7 @@ mod icons;
mod langpick;
mod launch;
mod list;
+mod lookwatch;
mod model;
mod native;
mod netwatch;
diff --git a/crates/app/src/native.rs b/crates/app/src/native.rs
index ee5b0a24..02690307 100644
--- a/crates/app/src/native.rs
+++ b/crates/app/src/native.rs
@@ -54,7 +54,8 @@ pub fn accent_palette_bytes(b: &[u8; 32]) -> [[u8; 3]; 7] {
out
}
-/// What the system says now (a few registry reads, or what the portal's thread last heard).
+/// What the system says (what the watcher of Windows' registry or the portal's thread last
+/// heard: never read on the window's thread, #719).
/// For tests and screenshots, `MDM_NATIVE_ACCENT=#rrggbb` stands for the system's accent and
/// `MDM_NATIVE_CONTRAST=1` for its high contrast, so no system setting is touched.
pub fn system(ctx: &egui::Context) -> System {
@@ -74,17 +75,7 @@ pub fn system(ctx: &egui::Context) -> System {
fn system_says(ctx: &egui::Context) -> System {
#[cfg(windows)]
{
- let _ = ctx;
- let rgb = |c: [u8; 3]| Color32::from_rgb(c[0], c[1], c[2]);
- System {
- accent: crate::win32::accent_palette().map(|p| Accent {
- base: rgb(p[3]),
- light: [rgb(p[2]), rgb(p[1]), rgb(p[0])],
- dark: [rgb(p[4]), rgb(p[5]), rgb(p[6])],
- }),
- high_contrast: crate::win32::high_contrast_colors(),
- more_contrast: false,
- }
+ crate::lookwatch::system(ctx).native
}
#[cfg(target_os = "linux")]
{
@@ -105,6 +96,22 @@ fn system_says(ctx: &egui::Context) -> System {
}
}
+/// What Windows says now: its accent from the registry, its high-contrast colours. For the
+/// thread that watches them (`lookwatch`): a registry read can wait for seconds.
+#[cfg(windows)]
+pub fn windows_now() -> System {
+ let rgb = |c: [u8; 3]| Color32::from_rgb(c[0], c[1], c[2]);
+ System {
+ accent: crate::win32::accent_palette().map(|p| Accent {
+ base: rgb(p[3]),
+ light: [rgb(p[2]), rgb(p[1]), rgb(p[0])],
+ dark: [rgb(p[4]), rgb(p[5]), rgb(p[6])],
+ }),
+ high_contrast: crate::win32::high_contrast_colors(),
+ more_contrast: false,
+ }
+}
+
/// The Native theme for what the system says.
pub fn theme(sys: &System) -> Theme {
if let Some([bg, text, selection, _selection_text, link, _greyed]) = sys.high_contrast {
diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs
index cbf1b37d..141ba936 100644
--- a/crates/app/src/theme.rs
+++ b/crates/app/src/theme.rs
@@ -109,37 +109,48 @@ pub fn select(id: &str, ctx: &egui::Context) -> Vec<String> {
}
}
-/// A theme file's theme, by its id or its path.
+/// A theme file's theme, by its id or its path; pywal's file followed from now on when the
+/// theme is made from it.
fn load(id: &str) -> Result<crate::themefile::Loaded, String> {
- let path = std::path::Path::new(id);
- if path.is_file() {
- crate::themefile::load_file(path)
- } else {
- crate::themefile::load(id)
+ let (loaded, followed) = crate::themefile::read(id);
+ if loaded.is_ok() {
+ crate::themefile::follow_pywal(followed);
}
+ loaded
}
/// The id (or path) [`select`] was last given.
static SELECTED: std::sync::Mutex<String> = std::sync::Mutex::new(String::new());
+/// The id (or path) of the theme chosen last.
+pub fn selected() -> String {
+ SELECTED.lock().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
/// While the theme is made from pywal's colours (#45): read again when `wal` wrote them anew,
-/// as it does for each new wallpaper. A file that doesn't read (half written as it was read)
-/// keeps the theme as it is, and is read again when it is next written. True when the theme
-/// changed (the caller applies it: `apply_theme`, `apply_mode`).
-pub fn follow_pywal() -> bool {
- if !crate::themefile::pywal_changed() {
+/// as it does for each new wallpaper; `lookwatch`'s thread reads it (#719), this takes what it
+/// read while the theme and the file it follows are still those it was read for. A file that
+/// doesn't read (half written as it was read) keeps the theme as it is, and is read again when
+/// it is next written. True when the theme changed (the caller applies it: `apply_theme`,
+/// `apply_mode`).
+pub fn follow_pywal(files: Option<&crate::lookwatch::ThemeFiles>) -> bool {
+ let Some(r) = files.and_then(|f| f.pywal.as_ref()) else {
+ return false;
+ };
+ if selected() != r.id || crate::themefile::following_pywal().as_ref() != Some(&r.followed) {
return false;
}
- let id = SELECTED.lock().unwrap_or_else(|e| e.into_inner()).clone();
- match load(&id) {
- Ok(loaded) => {
+ let id = &r.id;
+ match &r.read {
+ Ok((theme, _)) => {
tracing::info!("theme {id}: pywal's colours changed, read again");
- set(loaded.theme);
+ set(theme.clone());
+ crate::themefile::follow_pywal(r.follow.clone());
true
}
Err(e) => {
tracing::warn!("theme {id}: {e}; the theme kept until pywal's file is written again");
- crate::themefile::pywal_seen();
+ crate::themefile::pywal_seen_as(r.written);
false
}
}
@@ -213,12 +224,10 @@ pub fn system_theme(dark: bool) -> egui::SystemTheme {
/// appearance the window system reports (light when nothing says). True if it changed.
/// `always_dark` (View β†’ Always dark, #60): dark whatever the system says, for desktops that
/// report no preference.
+/// On Windows the registry is read by `lookwatch`'s thread, never this one (#719).
pub fn update(dark_mode_support: bool, always_dark: bool, ctx: &egui::Context) -> bool {
#[cfg(windows)]
- let system_dark = {
- let _ = ctx;
- crate::win32::apps_use_dark()
- };
+ let system_dark = crate::lookwatch::system(ctx).dark;
#[cfg(target_os = "linux")]
let system_dark = crate::unix::desktop_dark(ctx)
.unwrap_or_else(|| ctx.system_theme() == Some(egui::Theme::Dark));
@@ -228,19 +237,22 @@ pub fn update(dark_mode_support: bool, always_dark: bool, ctx: &egui::Context) -
DARK.swap(want, Ordering::Relaxed) != want
}
-/// Did the desktop say its look changed since the last call? On Linux, the portal's and the theme
-/// settings' watchers count each change (`unix::desktop_generation`), and the app's theme check,
-/// otherwise every 2 s, then runs in the frame the change woke (#156). Elsewhere false: the check's
-/// 2 s are its only clock there.
+/// Did the desktop say its look changed since the last call, or the theme files? The watchers
+/// count each change: on Linux the portal's and the theme settings' (`unix::desktop_generation`),
+/// everywhere `lookwatch`'s (Windows' registry, the themes folder, pywal's file). The app's theme
+/// check, otherwise every 2 s, then runs in the frame the change woke (#156, #719).
pub fn system_changed() -> bool {
+ static WATCHED: AtomicU64 = AtomicU64::new(0);
+ let now = crate::lookwatch::generation();
+ let watched = WATCHED.swap(now, Ordering::Relaxed) != now;
#[cfg(target_os = "linux")]
{
static SEEN: AtomicU64 = AtomicU64::new(0);
let now = crate::unix::desktop_generation();
- SEEN.swap(now, Ordering::Relaxed) != now
+ (SEEN.swap(now, Ordering::Relaxed) != now) | watched
}
#[cfg(not(target_os = "linux"))]
- false
+ watched
}
/// Dark or not: View β†’ Always dark, else the system's mode while Dark Mode support is on.
diff --git a/crates/app/src/themefile.rs b/crates/app/src/themefile.rs
index b2809527..8db3a45d 100644
--- a/crates/app/src/themefile.rs
+++ b/crates/app/src/themefile.rs
@@ -26,7 +26,9 @@
//!
//! A Base16 scheme (`.yaml`, `.yml`) and pywal's `colors.json` are themes too: `crate::schemes`
//! reads them into the same value tree, on the classic look. pywal's own file, where `wal`
-//! writes it, is the theme `pywal`, read again when `wal` changes it ([`pywal_changed`]).
+//! writes it, is the theme `pywal`, read again when `wal` changes it ([`following_pywal`]).
+//!
+//! The folder and pywal's file are looked at by `lookwatch`'s thread, never the window's (#719).
use std::path::{Path, PathBuf};
@@ -58,8 +60,14 @@ pub struct Entry {
/// The built-in themes, then pywal's colours when `wal` has written them, then the theme files
/// in [`dir`] (by name), each once: a file named as a built-in is skipped (the built-in keeps
-/// its id).
+/// its id). It reads every file of the folder: off the window's thread but for an action of the
+/// user's (View β†’ Theme β†’ Add a theme file).
pub fn list() -> Vec<Entry> {
+ list_in(dir().as_deref(), pywal_file())
+}
+
+/// [`list`] of the theme files in `dir`, with pywal's colours from `wal` when it is a file.
+pub fn list_in(dir: Option<&Path>, wal: Option<PathBuf>) -> Vec<Entry> {
let mut out: Vec<Entry> = palette::builtins()
.iter()
.map(|t| Entry {
@@ -68,7 +76,7 @@ pub fn list() -> Vec<Entry> {
path: None,
})
.collect();
- let mut files: Vec<(String, PathBuf)> = dir()
+ let mut files: Vec<(String, PathBuf)> = dir
.and_then(|d| std::fs::read_dir(d).ok())
.into_iter()
.flatten()
@@ -86,7 +94,7 @@ pub fn list() -> Vec<Entry> {
.collect();
files.sort();
// pywal's colours where `wal` keeps them, unless a file of the folder takes the name.
- if let Some(wal) = pywal_file().filter(|p| p.is_file())
+ if let Some(wal) = wal.filter(|p| p.is_file())
&& !files.iter().any(|(id, _)| id == PYWAL)
{
out.push(Entry {
@@ -115,9 +123,9 @@ pub fn list() -> Vec<Entry> {
out
}
-/// When the themes folder last changed (a file added, removed or renamed); None without one.
-pub fn changed() -> Option<std::time::SystemTime> {
- std::fs::metadata(dir()?).ok()?.modified().ok()
+/// When a themes folder last changed (a file added, removed or renamed); None without one.
+pub fn folder_stamp(dir: &Path) -> Option<std::time::SystemTime> {
+ std::fs::metadata(dir).ok()?.modified().ok()
}
/// A theme folder's file: `theme.toml` or `theme.json`.
@@ -163,13 +171,17 @@ pub fn pywal_file() -> Option<PathBuf> {
}
/// The file's time and size: what says it was written again.
-type Stamp = (Option<std::time::SystemTime>, u64);
+pub type Stamp = (Option<std::time::SystemTime>, u64);
+
+/// pywal's file as a theme was read from it, and its stamp then: the file to follow.
+pub type Followed = (PathBuf, Stamp);
/// pywal's file as last read for the active theme, with its stamp then: None when the active
/// theme isn't made from it.
-static PYWAL_READ: std::sync::Mutex<Option<(PathBuf, Stamp)>> = std::sync::Mutex::new(None);
+static PYWAL_READ: std::sync::Mutex<Option<Followed>> = std::sync::Mutex::new(None);
-fn stamp(path: &Path) -> Stamp {
+/// A file's [`Stamp`] (a look at its details on the disk).
+pub fn stamp(path: &Path) -> Stamp {
let meta = std::fs::metadata(path).ok();
(
meta.as_ref().and_then(|m| m.modified().ok()),
@@ -182,41 +194,60 @@ pub fn forget_pywal() {
*PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
-/// pywal's file as it is now taken as seen: a file that didn't read is read again only once it
+/// pywal's file taken as seen at `written`: a file that didn't read is read again only once it
/// is written again.
-pub fn pywal_seen() {
- if let Some((path, seen)) = PYWAL_READ
+pub fn pywal_seen_as(written: Stamp) {
+ if let Some((_, seen)) = PYWAL_READ
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_mut()
{
- *seen = stamp(path);
+ *seen = written;
}
}
-/// True when the active theme is made from pywal's file and `wal` has written it since (its
-/// time or size changed): one look at the file's details, on the main loop's 2-second check.
-pub fn pywal_changed() -> bool {
- let read = PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner());
- read.as_ref()
- .is_some_and(|(path, seen)| stamp(path) != *seen)
+/// The pywal file the active theme is made from, with its stamp when it was read; None when the
+/// theme isn't made from it. `lookwatch`'s thread compares it with the file's stamp now, and
+/// reads the theme again when `wal` has written it since (its time or size changed).
+pub fn following_pywal() -> Option<Followed> {
+ PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
-/// The theme with this id: a built-in, or the file of that name in [`dir`].
-pub fn load(id: &str) -> Result<Loaded, String> {
- let folder = dir().unwrap_or_default();
- load_in(&folder, id, 0)
+/// The active theme follows this pywal file from now on (None: none), as [`read`] found it.
+pub fn follow_pywal(followed: Option<Followed>) {
+ *PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner()) = followed;
}
-/// The theme in this file (the themes it inherits from beside it).
-pub fn load_file(path: &Path) -> Result<Loaded, String> {
- let id =
- theme_id(path).ok_or_else(|| format!("{}: not a .toml or .json file", path.display()))?;
- load_in(path.parent().unwrap_or(Path::new(".")), &id, 0)
+/// The theme with this id (a built-in, or the file of that name in [`dir`]) or in the theme
+/// file at this path (the themes it inherits from beside it); with pywal's file when the theme
+/// is made from it, to follow ([`follow_pywal`]).
+pub fn read(id: &str) -> (Result<Loaded, String>, Option<Followed>) {
+ let mut followed = None;
+ let path = Path::new(id);
+ let loaded = if path.is_file() {
+ match theme_id(path) {
+ Some(id) => load_in(
+ path.parent().unwrap_or(Path::new(".")),
+ &id,
+ 0,
+ &mut followed,
+ ),
+ None => Err(format!("{}: not a .toml or .json file", path.display())),
+ }
+ } else {
+ load_in(&dir().unwrap_or_default(), id, 0, &mut followed)
+ };
+ (loaded, followed)
}
-/// [`load`] from `folder`, `depth` themes down an `inherits` chain.
-fn load_in(folder: &Path, id: &str, depth: usize) -> Result<Loaded, String> {
+/// The theme `id` from `folder`, `depth` themes down an `inherits` chain; pywal's file into
+/// `followed` when one of them is read from it.
+fn load_in(
+ folder: &Path,
+ id: &str,
+ depth: usize,
+ followed: &mut Option<Followed>,
+) -> Result<Loaded, String> {
if let Some(t) = palette::builtins().into_iter().find(|t| t.id == id) {
return Ok(Loaded {
theme: t.clone(),
@@ -245,12 +276,14 @@ fn load_in(folder: &Path, id: &str, depth: usize) -> Result<Loaded, String> {
let before = wal.as_deref().map(stamp);
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
let (value, mut warnings) = read_value(&path, &text)?;
- let mut loaded = parse(id, &value, |base| load_in(folder, base, depth + 1))?;
+ let mut loaded = parse(id, &value, |base| {
+ load_in(folder, base, depth + 1, followed)
+ })?;
warnings.append(&mut loaded.warnings);
loaded.warnings = warnings;
// Followed from now on: read again when `wal` writes it.
if let (Some(wal), Some(seen)) = (wal, before) {
- *PYWAL_READ.lock().unwrap_or_else(|e| e.into_inner()) = Some((wal, seen));
+ *followed = Some((wal, seen));
}
// A theme folder's own icons (`<id>/icons/16`, `24`), unless the file names a set.
let icons = own.join("icons");
@@ -367,7 +400,7 @@ fn add_in(folder: &Path, source: &Path) -> Result<String, String> {
}
let target = folder.join(format!("{id}.{ext}"));
std::fs::write(&target, &bytes).map_err(|e| format!("{}: {e}", target.display()))?;
- if let Err(e) = load_in(folder, &id, 0) {
+ if let Err(e) = load_in(folder, &id, 0, &mut None) {
let _ = std::fs::remove_file(&target);
return Err(e);
}
@@ -647,6 +680,16 @@ mod tests {
use crate::palette::CLASSIC;
use egui::Color32;
+ /// [`super::load_in`], pywal's file not followed.
+ fn load_in(folder: &Path, id: &str, depth: usize) -> Result<Loaded, String> {
+ super::load_in(folder, id, depth, &mut None)
+ }
+
+ /// The theme in this file, as [`read`] gives it.
+ fn load_file(path: &Path) -> Result<Loaded, String> {
+ read(path.to_str().unwrap()).0
+ }
+
fn toml_theme(id: &str, text: &str) -> Result<Loaded, String> {
let v: Value = toml::from_str(text).map_err(|e| e.to_string())?;
parse(id, &v, |base| load_in(Path::new("nowhere"), base, 1))
@@ -854,17 +897,21 @@ mod tests {
let dir = temp_dir("wal-follow");
let file = dir.join("colors.json");
std::fs::write(&file, WAL).unwrap();
- *PYWAL_READ.lock().unwrap() = Some((file.clone(), stamp(&file)));
- assert!(!pywal_changed());
+ let changed = || following_pywal().is_some_and(|(path, seen)| stamp(&path) != seen);
+ follow_pywal(Some((file.clone(), stamp(&file))));
+ assert!(!changed());
// `wal` run again: other colours, another size.
std::fs::write(
&file,
WAL.replace("#3d6a9a", "#7b4d9e\", \"color5\": \"#000"),
)
.unwrap();
- assert!(pywal_changed());
+ assert!(changed());
+ // Taken as seen (a file that didn't read): not again until it is written again.
+ pywal_seen_as(stamp(&file));
+ assert!(!changed());
forget_pywal();
- assert!(!pywal_changed());
+ assert_eq!(following_pywal(), None);
let _ = std::fs::remove_dir_all(&dir);
}
diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rs
index d0f87d94..7f8a72c3 100644
--- a/crates/app/src/win32.rs
+++ b/crates/app/src/win32.rs
@@ -2685,13 +2685,22 @@ mod drag_thread_tests {
}
}
+/// The key of Windows' "Choose your app mode" (`AppsUseLightTheme`), under HKEY_CURRENT_USER.
+/// For tests, `MDM_PERSONALIZE_KEY` names another key to read it from (and to watch), so a check
+/// can switch the mode MDM sees without touching the system's.
+fn personalize_key() -> String {
+ std::env::var("MDM_PERSONALIZE_KEY")
+ .ok()
+ .filter(|k| !k.trim().is_empty())
+ .unwrap_or_else(|| r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize".into())
+}
+
/// Windows' "Choose your app mode": true when apps should be dark (`AppsUseLightTheme` = 0).
-/// Missing value (older Windows): light.
+/// Missing value (older Windows): light. A registry read, which can wait for seconds (#719): for
+/// a thread other than the window's (`lookwatch`).
pub fn apps_use_dark() -> bool {
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_DWORD, RegGetValueW};
- let key: Vec<u16> = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\0"
- .encode_utf16()
- .collect();
+ let key: Vec<u16> = personalize_key().encode_utf16().chain([0]).collect();
let name: Vec<u16> = "AppsUseLightTheme\0".encode_utf16().collect();
let mut value: u32 = 1;
let mut size = size_of::<u32>() as u32;
@@ -2738,6 +2747,110 @@ pub fn accent_palette() -> Option<[[u8; 3]; 7]> {
(rc == 0 && size >= 28).then(|| crate::native::accent_palette_bytes(&bytes))
}
+/// Waits for a change to what the theme follows in the registry (#719): the app mode
+/// ([`personalize_key`]), the accent colour, high contrast and the system colours, each key
+/// watched with `RegNotifyChangeKeyValue`. Opened, armed and waited on by `lookwatch`'s thread,
+/// never the window's: those calls can wait as long as a read.
+pub struct LookKeys {
+ /// The keys open for watching and the event each signals (HKEYs and HANDLEs, kept as numbers
+ /// so the watcher can be moved to its thread).
+ keys: Vec<(isize, isize)>,
+ /// Their notifications are registered (each fires once, and is registered again then).
+ armed: bool,
+}
+
+impl LookKeys {
+ /// The keys that exist (the accent's is missing on older Windows).
+ pub fn open() -> Self {
+ use windows_sys::Win32::System::Registry::{
+ HKEY, HKEY_CURRENT_USER, KEY_NOTIFY, RegCloseKey, RegOpenKeyExW,
+ };
+ use windows_sys::Win32::System::Threading::CreateEventW;
+ let paths = [
+ personalize_key(),
+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\Accent".into(),
+ r"Control Panel\Accessibility\HighContrast".into(),
+ r"Control Panel\Colors".into(),
+ ];
+ let keys = paths
+ .iter()
+ .filter_map(|p| {
+ let wide: Vec<u16> = p.encode_utf16().chain([0]).collect();
+ let mut h: HKEY = std::ptr::null_mut();
+ // SAFETY: opens a key into `h`, closed in Drop (or below).
+ let rc = unsafe {
+ RegOpenKeyExW(HKEY_CURRENT_USER, wide.as_ptr(), 0, KEY_NOTIFY, &mut h)
+ };
+ if rc != 0 {
+ return None;
+ }
+ // SAFETY: an unnamed auto-reset event, not signalled; closed in Drop.
+ let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
+ if event.is_null() {
+ // SAFETY: the key just opened, closed once.
+ unsafe { RegCloseKey(h) };
+ return None;
+ }
+ Some((h as isize, event as isize))
+ })
+ .collect();
+ LookKeys { keys, armed: false }
+ }
+
+ /// Wait until one of the keys changed, or `limit` passed (what the keys miss is read then).
+ pub fn wait(&mut self, limit: std::time::Duration) {
+ use windows_sys::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
+ use windows_sys::Win32::System::Registry::{
+ REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_THREAD_AGNOSTIC, RegNotifyChangeKeyValue,
+ };
+ use windows_sys::Win32::System::Threading::WaitForMultipleObjects;
+ if self.keys.is_empty() {
+ std::thread::sleep(limit);
+ return;
+ }
+ let arm = |(key, event): (isize, isize)| {
+ // SAFETY: an open key and its event; the notification is asynchronous, fires once and
+ // ends when the key is closed.
+ unsafe {
+ RegNotifyChangeKeyValue(
+ key as _,
+ 0,
+ REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC,
+ event as _,
+ 1,
+ )
+ };
+ };
+ if !self.armed {
+ self.keys.iter().copied().for_each(arm);
+ self.armed = true;
+ }
+ let events: Vec<HANDLE> = self.keys.iter().map(|&(_, e)| e as HANDLE).collect();
+ let ms = limit.as_millis().min(u128::from(u32::MAX - 1)) as u32;
+ // SAFETY: our own events, as many as the count says.
+ let rc = unsafe { WaitForMultipleObjects(events.len() as u32, events.as_ptr(), 0, ms) };
+ let fired = rc.wrapping_sub(WAIT_OBJECT_0) as usize;
+ if let Some(&k) = self.keys.get(fired) {
+ // Registered again before the read that follows, so a change during it is seen too.
+ arm(k);
+ }
+ }
+}
+
+impl Drop for LookKeys {
+ fn drop(&mut self) {
+ use windows_sys::Win32::Foundation::CloseHandle;
+ use windows_sys::Win32::System::Registry::RegCloseKey;
+ for &(key, event) in &self.keys {
+ // SAFETY: a key and an event made in `open`, each closed once.
+ unsafe {
+ RegCloseKey(key as _);
+ CloseHandle(event as _);
+ }
+ }
+ }
+}
+
/// Windows' high-contrast colours while high contrast is on (Settings β†’ Accessibility β†’
/// Contrast themes): background, text, selection, selection's text, links, greyed text. None
/// while it is off.