use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
use gtk::glib;
#[derive(Default, Clone)]
pub(crate) struct Debouncer {
pending: Rc<RefCell<HashMap<String, glib::SourceId>>>,
}
impl Debouncer {
#[must_use]
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn schedule(&self, path: String, delay: Duration, f: impl FnOnce() + 'static) {
if let Some(prev) = self.pending.borrow_mut().remove(&path) {
prev.remove();
}
let pending = Rc::clone(&self.pending);
let path_for_remove = path.clone();
let id = glib::timeout_add_local_once(delay, move || {
pending.borrow_mut().remove(&path_for_remove);
f();
});
self.pending.borrow_mut().insert(path, id);
}
pub(crate) fn flush(&self, path: &str, f: impl FnOnce()) {
if let Some(prev) = self.pending.borrow_mut().remove(path) {
prev.remove();
}
f();
}
}