use std::sync::mpsc;
use notify::Watcher;
use super::ThemeChangeEvent;
pub(super) const WATCHED_FILES: &[&str] = &["kdeglobals", "kcmfonts", "kdedefaults/kdeglobals"];
const KDEDEFAULTS: &str = "kdedefaults";
pub(crate) fn watch_kde(
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> crate::Result<super::ThemeSubscription> {
let config_dir =
crate::detect::xdg_config_home().ok_or_else(|| crate::Error::ReaderFailed {
reader: crate::error::reader_names::KDE_WATCHER,
source: crate::detect::CONFIG_HOME_UNRESOLVED.into(),
})?;
watch_kde_dir(config_dir, callback)
}
fn watch_kde_dir(
config_dir: std::path::PathBuf,
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> crate::Result<super::ThemeSubscription> {
let setup_failed = |step: &str, err: notify::Error| crate::Error::ReaderFailed {
reader: crate::error::reader_names::KDE_WATCHER,
source: format!("{step} failed for {}: {err}", config_dir.display()).into(),
};
let (tx, rx) = mpsc::channel();
let mut watcher =
notify::recommended_watcher(tx).map_err(|err| setup_failed("creating the watcher", err))?;
watcher
.watch(&config_dir, notify::RecursiveMode::NonRecursive)
.map_err(|err| setup_failed("watching the config directory", err))?;
let defaults_dir = config_dir.join(KDEDEFAULTS);
let _ = watcher.watch(&defaults_dir, notify::RecursiveMode::NonRecursive);
let watched_paths: Vec<std::path::PathBuf> = WATCHED_FILES
.iter()
.map(|file| config_dir.join(file))
.collect();
let (shutdown_tx, shutdown_rx) = mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
let is_relevant = |event: notify::Result<notify::Event>| {
let Ok(event) = event else {
return false;
};
let is_mutation = matches!(
event.kind,
notify::EventKind::Modify(_)
| notify::EventKind::Create(_)
| notify::EventKind::Remove(_)
);
if !is_mutation {
return false;
}
let defaults_created = matches!(event.kind, notify::EventKind::Create(_))
&& event.paths.contains(&defaults_dir);
if defaults_created {
let _ = watcher.watch(&defaults_dir, notify::RecursiveMode::NonRecursive);
}
defaults_created || event.paths.iter().any(|path| watched_paths.contains(path))
};
super::fire_debounced(&rx, &shutdown_rx, is_relevant, &callback);
});
Ok(super::ThemeSubscription::new(shutdown_tx, thread, None))
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant};
const TIMEOUT: Duration = Duration::from_secs(5);
struct TempConfigDir(std::path::PathBuf);
impl Drop for TempConfigDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn temp_config_dir(tag: &str) -> TempConfigDir {
let dir = std::env::temp_dir().join(format!(
"native-theme-kde-watcher-{}-{tag}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("kdeglobals"), "[General]\n").unwrap();
TempConfigDir(dir)
}
fn write_kdeglobals(dir: &TempConfigDir, round: usize) {
std::fs::write(
dir.0.join("kdeglobals"),
format!("[General]\nround={round}\n"),
)
.unwrap();
}
fn drop_returns(subscription: super::super::ThemeSubscription) -> bool {
let (done_tx, done_rx) = mpsc::channel();
std::thread::spawn(move || {
drop(subscription);
let _ = done_tx.send(());
});
done_rx.recv_timeout(TIMEOUT).is_ok()
}
#[test]
fn an_unwatchable_directory_is_an_error() {
let dir = temp_config_dir("unwatchable");
let missing = dir.0.join("missing");
let result = super::watch_kde_dir(missing, |_| {});
assert!(
matches!(
&result,
Err(crate::Error::ReaderFailed {
reader: crate::error::reader_names::KDE_WATCHER,
..
})
),
"expected ReaderFailed from kde-watcher, got: {result:?}"
);
}
#[test]
fn a_burst_of_writes_fires_after_the_last() {
let dir = temp_config_dir("burst");
let (event_tx, event_rx) = mpsc::channel();
let subscription = super::watch_kde_dir(dir.0.clone(), move |_| {
let _ = event_tx.send(Instant::now());
})
.unwrap();
let mut before_last_write = Instant::now();
for round in 0..6 {
if round > 0 {
std::thread::sleep(Duration::from_millis(50));
}
before_last_write = Instant::now();
write_kdeglobals(&dir, round);
}
let due = before_last_write + super::super::DEBOUNCE;
let deadline = Instant::now() + TIMEOUT;
loop {
let fired = event_rx
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.expect("no event the debounce window after the last write");
if fired >= due {
break;
}
}
assert!(drop_returns(subscription));
}
#[test]
fn a_write_to_kdedefaults_fires() {
let dir = temp_config_dir("kdedefaults");
std::fs::create_dir_all(dir.0.join("kdedefaults")).unwrap();
let (event_tx, event_rx) = mpsc::channel();
let subscription = super::watch_kde_dir(dir.0.clone(), move |_| {
let _ = event_tx.send(());
})
.unwrap();
std::fs::write(
dir.0.join("kdedefaults/kdeglobals"),
"[Icons]\nTheme=breeze\n",
)
.unwrap();
assert!(
event_rx.recv_timeout(TIMEOUT).is_ok(),
"no event after kdedefaults/kdeglobals changed"
);
assert!(drop_returns(subscription));
}
#[test]
fn a_kdedefaults_created_later_is_watched() {
let dir = temp_config_dir("kdedefaults-later");
let (event_tx, event_rx) = mpsc::channel();
let subscription = super::watch_kde_dir(dir.0.clone(), move |_| {
let _ = event_tx.send(());
})
.unwrap();
std::fs::create_dir_all(dir.0.join("kdedefaults")).unwrap();
assert!(
event_rx.recv_timeout(TIMEOUT).is_ok(),
"no event after kdedefaults was created"
);
std::fs::write(
dir.0.join("kdedefaults/kdeglobals"),
"[Icons]\nTheme=breeze\n",
)
.unwrap();
assert!(
event_rx.recv_timeout(TIMEOUT).is_ok(),
"no event after kdedefaults/kdeglobals changed"
);
assert!(drop_returns(subscription));
}
#[test]
fn dropping_during_a_burst_returns() {
let dir = temp_config_dir("drop-burst");
let subscription = super::watch_kde_dir(dir.0.clone(), |_| {}).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let writer = {
let stop = Arc::clone(&stop);
let path = dir.0.clone();
std::thread::spawn(move || {
let mut round = 0usize;
while !stop.load(Ordering::SeqCst) {
let _ = std::fs::write(path.join("kdeglobals"), format!("round={round}\n"));
round += 1;
std::thread::sleep(Duration::from_millis(50));
}
})
};
std::thread::sleep(Duration::from_millis(500));
let returned = drop_returns(subscription);
stop.store(true, Ordering::SeqCst);
writer.join().unwrap();
assert!(
returned,
"dropping the KDE subscription during a burst did not return within {TIMEOUT:?}"
);
}
#[test]
fn a_panicking_callback_does_not_stop_the_watcher() {
let dir = temp_config_dir("panic");
let calls = Arc::new(AtomicUsize::new(0));
let (event_tx, event_rx) = mpsc::channel();
let subscription = {
let calls = Arc::clone(&calls);
super::watch_kde_dir(dir.0.clone(), move |_| {
let call = calls.fetch_add(1, Ordering::SeqCst);
let _ = event_tx.send(call);
assert!(call > 0, "the first callback panics");
})
.unwrap()
};
write_kdeglobals(&dir, 0);
assert_eq!(event_rx.recv_timeout(TIMEOUT).unwrap(), 0);
std::thread::sleep(Duration::from_millis(500));
write_kdeglobals(&dir, 1);
assert_eq!(
event_rx.recv_timeout(TIMEOUT).ok(),
Some(1),
"no event after the callback panicked"
);
assert!(drop_returns(subscription));
}
#[test]
fn a_callback_that_drops_its_subscription_returns_and_the_thread_exits() {
struct OnDrop(mpsc::Sender<()>);
impl Drop for OnDrop {
fn drop(&mut self) {
let _ = self.0.send(());
}
}
let dir = temp_config_dir("drop-in-callback");
let slot: Arc<std::sync::Mutex<Option<super::super::ThemeSubscription>>> =
Arc::new(std::sync::Mutex::new(None));
let (dropped_tx, dropped_rx) = mpsc::channel();
let (exited_tx, exited_rx) = mpsc::channel();
let subscription = {
let slot = Arc::clone(&slot);
let exited = OnDrop(exited_tx);
super::watch_kde_dir(dir.0.clone(), move |_| {
let _ = &exited;
let subscription = slot.lock().unwrap().take();
drop(subscription);
let _ = dropped_tx.send(());
})
.unwrap()
};
*slot.lock().unwrap() = Some(subscription);
write_kdeglobals(&dir, 0);
assert!(
dropped_rx.recv_timeout(TIMEOUT).is_ok(),
"dropping the subscription from its own callback did not return"
);
assert!(
exited_rx.recv_timeout(TIMEOUT).is_ok(),
"the watcher thread did not exit after its callback dropped the subscription"
);
}
}