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) {
let prev = self.pending.borrow_mut().remove(&path);
if let Some(prev) = prev {
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()) {
let prev = self.pending.borrow_mut().remove(path);
if let Some(prev) = prev {
prev.remove();
}
f();
}
pub(crate) fn cancel_all(&self) {
let drained: Vec<glib::SourceId> = self
.pending
.borrow_mut()
.drain()
.map(|(_, id)| id)
.collect();
for id in drained {
id.remove();
}
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::time::Instant;
use super::*;
fn schedule_counters(debouncer: &Debouncer, fired: &Rc<Cell<u32>>) {
for path in ["bg.blur.radius", "fg.sharpen.amount"] {
let fired = Rc::clone(fired);
debouncer.schedule(path.to_string(), Duration::from_millis(10), move || {
fired.set(fired.get() + 1);
});
}
}
fn run_default_context_past_delay() {
let ctx = glib::MainContext::default();
let deadline = Instant::now() + Duration::from_millis(60);
while Instant::now() < deadline {
ctx.iteration(false);
std::thread::sleep(Duration::from_millis(2));
}
}
#[test]
fn cancel_all_drops_every_pending_callback() {
let fired = Rc::new(Cell::new(0_u32));
let debouncer = Debouncer::new();
schedule_counters(&debouncer, &fired);
run_default_context_past_delay();
assert_eq!(fired.get(), 2, "control: callbacks fire without cancel_all");
assert!(debouncer.pending.borrow().is_empty());
fired.set(0);
schedule_counters(&debouncer, &fired);
debouncer.cancel_all();
assert!(debouncer.pending.borrow().is_empty());
run_default_context_past_delay();
assert_eq!(fired.get(), 0, "cancel_all must drop pending callbacks");
}
}