use std::sync::mpsc;
use std::time::{Duration, Instant};
use notify::Watcher;
use super::ThemeChangeEvent;
#[allow(dead_code)] pub(crate) fn watch_kde(
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> crate::Result<super::ThemeSubscription> {
let kdeglobals = crate::kde::kdeglobals_path();
let config_dir = kdeglobals
.parent()
.ok_or_else(|| crate::Error::ReaderFailed {
reader: "kde_watcher",
source: "no parent directory for kdeglobals path".into(),
})?
.to_path_buf();
let watched_names: &[&std::ffi::OsStr] = &[
std::ffi::OsStr::new("kdeglobals"),
std::ffi::OsStr::new("kcmfontsrc"),
];
let watched_names: Vec<std::ffi::OsString> =
watched_names.iter().map(|n| (*n).to_os_string()).collect();
let (shutdown_tx, shutdown_rx) = mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
let (tx, rx) = mpsc::channel();
let mut _watcher = match notify::recommended_watcher(tx) {
Ok(w) => w,
Err(_) => return,
};
if _watcher
.watch(&config_dir, notify::RecursiveMode::NonRecursive)
.is_err()
{
return;
}
let mut last_fire: Option<Instant> = None;
let debounce = Duration::from_millis(300);
loop {
match rx.recv_timeout(Duration::from_millis(200)) {
Ok(Ok(event)) => {
let is_mutation = matches!(
event.kind,
notify::EventKind::Modify(_)
| notify::EventKind::Create(_)
| notify::EventKind::Remove(_)
);
if !is_mutation {
continue;
}
let is_relevant = event.paths.iter().any(|p| {
p.file_name()
.is_some_and(|n| watched_names.iter().any(|w| *w == n))
});
if is_relevant && last_fire.is_none_or(|t| t.elapsed() >= debounce) {
last_fire = Some(Instant::now());
callback(ThemeChangeEvent::Changed);
}
}
Ok(Err(_)) => {
}
Err(mpsc::RecvTimeoutError::Timeout) => {
match shutdown_rx.try_recv() {
Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
Err(mpsc::TryRecvError::Empty) => {}
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
break;
}
}
}
});
Ok(super::ThemeSubscription::new(shutdown_tx, thread, None))
}