use super::{REG, flush_models, guarded, wake_answered, with};
use crate::backend::{Backend, Native as B};
use crate::layout;
use crate::types::WidgetId;
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
type Job = Box<dyn FnOnce() + Send>;
#[derive(Default)]
struct Queue {
jobs: VecDeque<Job>,
wake_pending: bool,
}
static QUEUES: Mutex<Option<HashMap<std::thread::ThreadId, Queue>>> = Mutex::new(None);
pub(super) static UI_THREAD: Mutex<Option<std::thread::ThreadId>> = Mutex::new(None);
pub fn post(f: impl FnOnce() + Send + 'static) {
let own = REG
.try_with(|c| c.try_borrow().map_or(true, |g| g.is_some()))
.unwrap_or(false);
let me = std::thread::current().id();
let target = if own {
me
} else {
UI_THREAD
.lock()
.unwrap_or_else(|e| e.into_inner())
.unwrap_or(me)
};
post_to(target, f);
}
pub fn post_to(target: std::thread::ThreadId, f: impl FnOnce() + Send + 'static) {
let need_wake = {
let mut queues = QUEUES.lock().unwrap_or_else(|e| e.into_inner());
let q = queues
.get_or_insert_with(HashMap::new)
.entry(target)
.or_default();
q.jobs.push_back(Box::new(f));
!std::mem::replace(&mut q.wake_pending, true)
};
if need_wake {
B::wake();
}
}
pub fn drain_posted() {
wake_answered();
let me = std::thread::current().id();
let batch = QUEUES
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_mut()
.and_then(|m| m.get_mut(&me))
.map(|q| {
q.wake_pending = false;
std::mem::take(&mut q.jobs)
})
.unwrap_or_default();
for job in batch {
guarded(job);
}
flush();
}
pub fn flush() {
flush_models();
for _ in 0..4 {
let (lay, a11y) = match with(|r| {
r.scheduled = false;
(
std::mem::take(&mut r.dirty_layout),
std::mem::take(&mut r.dirty_a11y),
)
}) {
Some(x) => x,
None => return,
};
if lay.is_empty() && a11y.is_empty() {
return;
}
for w in lay {
layout_window(w);
}
for w in a11y {
if with(|r| r.nodes.contains_key(&w)).unwrap_or(false) {
B::a11y_changed(w);
}
}
}
}
pub fn layout_window(w: WidgetId) {
let jobs = with(|r| layout::compute(r, w)).unwrap_or_default();
for (id, prop) in jobs {
B::set(id, &prop);
}
}