use std::cell::Cell;
use std::sync::{Arc, Condvar, Mutex};
use std::time;
use log::warn;
use servo::embedder_traits::EventLoopWaker;
use winit::error::EventLoopError;
use winit::event_loop::{ActiveEventLoop, EventLoop as WinitEventLoop};
#[cfg(target_os = "macos")]
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
use super::app::App;
#[derive(Debug)]
pub struct WakerEvent;
#[allow(dead_code)]
enum EventLoop {
Winit(Option<winit::event_loop::EventLoop<WakerEvent>>),
Headless(Arc<(Mutex<bool>, Condvar)>),
}
pub struct EventsLoop(EventLoop);
impl EventsLoop {
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn new(_headless: bool, _has_output_file: bool) -> Result<EventsLoop, EventLoopError> {
Ok(EventsLoop(EventLoop::Winit(Some(
WinitEventLoop::with_user_event().build()?,
))))
}
#[cfg(target_os = "linux")]
pub fn new(headless: bool, _has_output_file: bool) -> Result<EventsLoop, EventLoopError> {
Ok(EventsLoop(if headless {
EventLoop::Headless(Arc::new((Mutex::new(false), Condvar::new())))
} else {
EventLoop::Winit(Some(WinitEventLoop::with_user_event().build()?))
}))
}
#[cfg(target_os = "macos")]
pub fn new(headless: bool, _has_output_file: bool) -> Result<EventsLoop, EventLoopError> {
Ok(EventsLoop(if headless {
EventLoop::Headless(Arc::new((Mutex::new(false), Condvar::new())))
} else {
let mut event_loop_builder = WinitEventLoop::with_user_event();
if _has_output_file {
event_loop_builder.with_activation_policy(ActivationPolicy::Prohibited);
}
EventLoop::Winit(Some(event_loop_builder.build()?))
}))
}
}
impl EventsLoop {
pub fn create_event_loop_waker(&self) -> Box<dyn EventLoopWaker> {
match self.0 {
EventLoop::Winit(ref events_loop) => {
let events_loop = events_loop
.as_ref()
.expect("Can't create waker for unavailable event loop.");
Box::new(HeadedEventLoopWaker::new(events_loop))
},
EventLoop::Headless(ref data) => Box::new(HeadlessEventLoopWaker(data.clone())),
}
}
pub fn as_winit(&self) -> &WinitEventLoop<WakerEvent> {
match self.0 {
EventLoop::Winit(Some(ref event_loop)) => event_loop,
EventLoop::Winit(None) | EventLoop::Headless(..) => {
panic!("Can't access winit event loop while using the fake headless event loop")
},
}
}
pub fn run_app(self, app: &mut App) {
match self.0 {
EventLoop::Winit(events_loop) => {
let events_loop = events_loop.expect("Can't run an unavailable event loop.");
events_loop
.run_app(app)
.expect("Failed while running events loop");
},
EventLoop::Headless(ref data) => {
let (flag, condvar) = &**data;
app.init();
loop {
self.sleep(flag, condvar);
if app.handle_events_with_headless() {
break;
}
if !app.is_animating() {
*flag.lock().unwrap() = false;
}
}
},
}
}
fn sleep(&self, lock: &Mutex<bool>, condvar: &Condvar) {
let guard = lock.lock().unwrap();
if *guard {
return;
}
let _ = condvar
.wait_timeout(guard, time::Duration::from_millis(5))
.unwrap();
}
}
struct HeadedEventLoopWaker {
proxy: Arc<Mutex<winit::event_loop::EventLoopProxy<WakerEvent>>>,
}
impl HeadedEventLoopWaker {
fn new(events_loop: &winit::event_loop::EventLoop<WakerEvent>) -> HeadedEventLoopWaker {
let proxy = Arc::new(Mutex::new(events_loop.create_proxy()));
HeadedEventLoopWaker { proxy }
}
}
impl EventLoopWaker for HeadedEventLoopWaker {
fn wake(&self) {
if let Err(err) = self.proxy.lock().unwrap().send_event(WakerEvent) {
warn!("Failed to wake up event loop ({}).", err);
}
}
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
Box::new(HeadedEventLoopWaker {
proxy: self.proxy.clone(),
})
}
}
struct HeadlessEventLoopWaker(Arc<(Mutex<bool>, Condvar)>);
impl EventLoopWaker for HeadlessEventLoopWaker {
fn wake(&self) {
let (ref flag, ref condvar) = *self.0;
let mut flag = flag.lock().unwrap();
*flag = true;
condvar.notify_all();
}
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
Box::new(HeadlessEventLoopWaker(self.0.clone()))
}
}
thread_local! {
static CURRENT_EVENT_LOOP: Cell<Option<*const ActiveEventLoop>> = const { Cell::new(None) };
}
pub struct EventLoopGuard;
impl EventLoopGuard {
pub fn new(event_loop: &ActiveEventLoop) -> Self {
CURRENT_EVENT_LOOP.with(|cell| {
assert!(
cell.get().is_none(),
"Attempted to set a new event loop while one is already set"
);
cell.set(Some(event_loop as *const ActiveEventLoop));
});
Self
}
}
impl Drop for EventLoopGuard {
fn drop(&mut self) {
CURRENT_EVENT_LOOP.with(|cell| cell.set(None));
}
}
#[allow(unsafe_code)]
pub fn with_current_event_loop<F, R>(f: F) -> Option<R>
where
F: FnOnce(&ActiveEventLoop) -> R,
{
CURRENT_EVENT_LOOP.with(|cell| {
cell.get().map(|ptr| {
let event_loop = unsafe { &*ptr };
f(event_loop)
})
})
}