use std::sync::Weak;
use std::thread::{self, ThreadId};
use super::{BackgroundThread, EventLoop, MainThreadExecutor};
use crate::nice_debug_assert_failure;
use crate::util::permit_alloc;
pub(crate) struct LinuxEventLoop<T, E> {
executor: Weak<E>,
background_thread: BackgroundThread<T, E>,
main_thread_id: ThreadId,
}
impl<T, E> EventLoop<T, E> for LinuxEventLoop<T, E>
where
T: Send + 'static,
E: MainThreadExecutor<T> + 'static,
{
fn new_and_spawn(executor: Weak<E>) -> Self {
Self {
executor: executor.clone(),
background_thread: BackgroundThread::get_or_create(executor),
main_thread_id: thread::current().id(),
}
}
fn schedule_gui(&self, task: T) -> bool {
if self.is_main_thread() {
match self.executor.upgrade() {
Some(executor) => executor.execute(task, true),
None => {
nice_debug_assert_failure!("GUI task was posted after the executor was dropped")
}
}
true
} else {
self.background_thread.schedule(task)
}
}
fn schedule_background(&self, task: T) -> bool {
self.background_thread.schedule(task)
}
fn is_main_thread(&self) -> bool {
permit_alloc(|| thread::current().id() == self.main_thread_id)
}
}