use crate::kept::{UiCell, UiLocal};
use crate::ViewId;
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
FocusStep {
forward: bool,
},
FocusChanged(Option<ViewId>),
AppearanceChanged,
Action(ViewId),
Redraw,
}
type Sink = Box<dyn Fn(Event)>;
thread_local! {
static SINK: UiCell<Option<Sink>> = const { UiCell::new(None) };
}
pub fn set_event_sink(sink: impl Fn(Event) + 'static) {
SINK.with_borrow_mut(|s| *s = Some(Box::new(sink)));
}
pub(crate) fn emit(event: Event) -> bool {
SINK.with_borrow(|s| match s {
Some(sink) => {
sink(event);
true
}
None => false,
})
}
thread_local! {
static REDRAW_QUEUED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn request_redraw() {
if !REDRAW_QUEUED.with(|q| q.replace(true)) && !emit(Event::Redraw) {
REDRAW_QUEUED.with(|q| q.set(false));
}
}
pub(crate) fn frame_started() {
REDRAW_QUEUED.with(|q| q.set(false));
}
#[cfg(test)]
mod tests {
use super::*;
use std::rc::Rc;
#[test]
fn an_early_redraw_request_doesnt_block_later_ones() {
request_redraw();
let redraws = Rc::new(std::cell::Cell::new(0));
let r = redraws.clone();
set_event_sink(move |e| {
if e == Event::Redraw {
r.set(r.get() + 1);
}
});
request_redraw();
request_redraw();
assert_eq!(redraws.get(), 1, "one per frame");
frame_started();
request_redraw();
assert_eq!(redraws.get(), 2);
}
}