winit-sonoma-fix/src/platform/linux/wayland/event_loop.rs

467 lines
15 KiB
Rust
Raw Normal View History

use std::cell::RefCell;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, Weak};
use std::sync::atomic::{AtomicBool, Ordering};
use {ControlFlow, EventsLoopClosed};
2017-03-05 00:04:01 +11:00
use super::WindowId;
use super::window::WindowStore;
2017-03-05 00:04:01 +11:00
use sctk::Environment;
use sctk::output::OutputMgr;
use sctk::reexports::client::{Display, EventQueue, GlobalEvent, Proxy, ConnectError};
use sctk::reexports::client::commons::Implementation;
use sctk::reexports::client::protocol::{wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat,
wl_touch};
use sctk::reexports::client::protocol::wl_display::RequestsTrait as DisplayRequests;
2017-03-05 00:04:01 +11:00
pub struct EventsLoopSink {
buffer: VecDeque<::Event>,
2017-03-05 00:04:01 +11:00
}
impl EventsLoopSink {
pub fn new() -> EventsLoopSink {
EventsLoopSink {
buffer: VecDeque::new(),
}
2017-03-05 00:04:01 +11:00
}
pub fn send_event(&mut self, evt: ::WindowEvent, wid: WindowId) {
2017-03-05 00:04:01 +11:00
let evt = ::Event::WindowEvent {
event: evt,
window_id: ::WindowId(::platform::WindowId::Wayland(wid)),
2017-03-05 00:04:01 +11:00
};
self.buffer.push_back(evt);
2017-03-05 00:04:01 +11:00
}
pub fn send_raw_event(&mut self, evt: ::Event) {
self.buffer.push_back(evt);
2017-03-05 00:04:01 +11:00
}
fn empty_with<F>(&mut self, callback: &mut F)
where
F: FnMut(::Event),
{
for evt in self.buffer.drain(..) {
callback(evt)
}
2017-03-05 00:04:01 +11:00
}
}
pub struct EventsLoop {
// The Event Queue
pub evq: RefCell<EventQueue>,
// our sink, shared with some handlers, buffering the events
2017-03-05 00:04:01 +11:00
sink: Arc<Mutex<EventsLoopSink>>,
// Whether or not there is a pending `Awakened` event to be emitted.
pending_wakeup: Arc<AtomicBool>,
// The window store
pub store: Arc<Mutex<WindowStore>>,
// the env
pub env: Environment,
// a cleanup switch to prune dead windows
pub cleanup_needed: Arc<Mutex<bool>>,
// The wayland display
pub display: Arc<Display>,
// The list of seats
pub seats: Arc<Mutex<Vec<(u32, Proxy<wl_seat::WlSeat>)>>>,
}
// A handle that can be sent across threads and used to wake up the `EventsLoop`.
//
// We should only try and wake up the `EventsLoop` if it still exists, so we hold Weak ptrs.
2017-10-26 05:03:57 +11:00
#[derive(Clone)]
pub struct EventsLoopProxy {
display: Weak<Display>,
pending_wakeup: Weak<AtomicBool>,
}
impl EventsLoopProxy {
// Causes the `EventsLoop` to stop blocking on `run_forever` and emit an `Awakened` event.
//
// Returns `Err` if the associated `EventsLoop` no longer exists.
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
let display = self.display.upgrade();
let wakeup = self.pending_wakeup.upgrade();
match (display, wakeup) {
(Some(display), Some(wakeup)) => {
// Update the `EventsLoop`'s `pending_wakeup` flag.
wakeup.store(true, Ordering::Relaxed);
// Cause the `EventsLoop` to break from `dispatch` if it is currently blocked.
let _ = display.sync();
display.flush().map_err(|_| EventsLoopClosed)?;
Ok(())
}
_ => Err(EventsLoopClosed),
}
}
2017-03-05 00:04:01 +11:00
}
impl EventsLoop {
pub fn new() -> Result<EventsLoop, ConnectError> {
let (display, mut event_queue) = Display::connect_to_env()?;
let sink = Arc::new(Mutex::new(EventsLoopSink::new()));
let store = Arc::new(Mutex::new(WindowStore::new()));
let seats = Arc::new(Mutex::new(Vec::new()));
let env = Environment::from_registry_with_cb(
display.get_registry().unwrap(),
&mut event_queue,
SeatManager {
sink: sink.clone(),
store: store.clone(),
seats: seats.clone(),
},
).unwrap();
Ok(EventsLoop {
display: Arc::new(display),
evq: RefCell::new(event_queue),
sink: sink,
pending_wakeup: Arc::new(AtomicBool::new(false)),
store: store,
env: env,
cleanup_needed: Arc::new(Mutex::new(false)),
seats: seats,
})
}
pub fn create_proxy(&self) -> EventsLoopProxy {
EventsLoopProxy {
display: Arc::downgrade(&self.display),
pending_wakeup: Arc::downgrade(&self.pending_wakeup),
}
}
pub fn poll_events<F>(&mut self, mut callback: F)
where
F: FnMut(::Event),
2017-03-05 00:04:01 +11:00
{
// send pending events to the server
self.display.flush().expect("Wayland connection lost.");
2017-03-05 00:04:01 +11:00
// dispatch any pre-buffered events
self.sink.lock().unwrap().empty_with(&mut callback);
2017-03-05 00:04:01 +11:00
// try to read pending events
if let Some(h) = self.evq.get_mut().prepare_read() {
h.read_events().expect("Wayland connection lost.");
}
// dispatch wayland events
self.evq
.get_mut()
.dispatch_pending()
.expect("Wayland connection lost.");
self.post_dispatch_triggers();
// dispatch buffered events to client
self.sink.lock().unwrap().empty_with(&mut callback);
2017-03-05 00:04:01 +11:00
}
pub fn run_forever<F>(&mut self, mut callback: F)
where
F: FnMut(::Event) -> ControlFlow,
2017-03-05 00:04:01 +11:00
{
// send pending events to the server
self.display.flush().expect("Wayland connection lost.");
2017-03-05 00:04:01 +11:00
// Check for control flow by wrapping the callback.
let control_flow = ::std::cell::Cell::new(ControlFlow::Continue);
let mut callback = |event| {
if let ControlFlow::Break = callback(event) {
control_flow.set(ControlFlow::Break);
}
};
// dispatch any pre-buffered events
self.post_dispatch_triggers();
self.sink.lock().unwrap().empty_with(&mut callback);
2017-03-05 00:04:01 +11:00
loop {
// dispatch events blocking if needed
self.evq
.get_mut()
.dispatch()
.expect("Wayland connection lost.");
self.post_dispatch_triggers();
// empty buffer of events
self.sink.lock().unwrap().empty_with(&mut callback);
2017-03-11 09:56:31 +11:00
if let ControlFlow::Break = control_flow.get() {
break;
}
2017-03-05 00:04:01 +11:00
}
}
pub fn get_primary_monitor(&self) -> MonitorId {
self.env.outputs.with_all(|list| {
if let Some(&(_, ref proxy, _)) = list.first() {
MonitorId {
proxy: proxy.clone(),
mgr: self.env.outputs.clone(),
}
} else {
panic!("No monitor is available.")
}
})
}
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
self.env.outputs.with_all(|list| {
list.iter()
.map(|&(_, ref proxy, _)| MonitorId {
proxy: proxy.clone(),
mgr: self.env.outputs.clone(),
})
.collect()
})
}
}
/*
* Private EventsLoop Internals
*/
impl EventsLoop {
fn post_dispatch_triggers(&mut self) {
let mut sink = self.sink.lock().unwrap();
// process a possible pending wakeup call
if self.pending_wakeup.load(Ordering::Relaxed) {
sink.send_raw_event(::Event::Awakened);
self.pending_wakeup.store(false, Ordering::Relaxed);
}
// prune possible dead windows
{
let mut cleanup_needed = self.cleanup_needed.lock().unwrap();
if *cleanup_needed {
let pruned = self.store.lock().unwrap().cleanup();
*cleanup_needed = false;
for wid in pruned {
sink.send_event(::WindowEvent::Destroyed, wid);
}
}
}
// process pending resize/refresh
self.store.lock().unwrap().for_each(
|newsize, refresh, frame_refresh, closed, wid, frame| {
if let Some(frame) = frame {
if let Some((w, h)) = newsize {
frame.resize(w as u32, h as u32);
frame.refresh();
sink.send_event(::WindowEvent::Resized(w as u32, h as u32), wid);
} else if frame_refresh {
frame.refresh();
}
}
if refresh {
sink.send_event(::WindowEvent::Refresh, wid);
}
if closed {
sink.send_event(::WindowEvent::CloseRequested, wid);
}
},
)
}
}
/*
* Wayland protocol implementations
*/
struct SeatManager {
sink: Arc<Mutex<EventsLoopSink>>,
store: Arc<Mutex<WindowStore>>,
seats: Arc<Mutex<Vec<(u32, Proxy<wl_seat::WlSeat>)>>>,
}
impl Implementation<Proxy<wl_registry::WlRegistry>, GlobalEvent> for SeatManager {
fn receive(&mut self, evt: GlobalEvent, registry: Proxy<wl_registry::WlRegistry>) {
use self::wl_registry::RequestsTrait as RegistryRequests;
use self::wl_seat::RequestsTrait as SeatRequests;
match evt {
GlobalEvent::New {
id,
ref interface,
version,
} if interface == "wl_seat" =>
{
use std::cmp::min;
let seat = registry
.bind::<wl_seat::WlSeat>(min(version, 5), id)
.unwrap()
.implement(SeatData {
sink: self.sink.clone(),
store: self.store.clone(),
pointer: None,
keyboard: None,
touch: None,
});
self.store.lock().unwrap().new_seat(&seat);
self.seats.lock().unwrap().push((id, seat));
}
GlobalEvent::Removed { id, ref interface } if interface == "wl_seat" => {
let mut seats = self.seats.lock().unwrap();
if let Some(idx) = seats.iter().position(|&(i, _)| i == id) {
let (_, seat) = seats.swap_remove(idx);
if seat.version() >= 5 {
seat.release();
}
}
}
_ => (),
}
}
}
struct SeatData {
sink: Arc<Mutex<EventsLoopSink>>,
store: Arc<Mutex<WindowStore>>,
pointer: Option<Proxy<wl_pointer::WlPointer>>,
keyboard: Option<Proxy<wl_keyboard::WlKeyboard>>,
touch: Option<Proxy<wl_touch::WlTouch>>,
}
impl Implementation<Proxy<wl_seat::WlSeat>, wl_seat::Event> for SeatData {
fn receive(&mut self, evt: wl_seat::Event, seat: Proxy<wl_seat::WlSeat>) {
use self::wl_seat::RequestsTrait as SeatRequests;
match evt {
wl_seat::Event::Name { .. } => (),
wl_seat::Event::Capabilities { capabilities } => {
// create pointer if applicable
if capabilities.contains(wl_seat::Capability::Pointer) && self.pointer.is_none() {
self.pointer = Some(super::pointer::implement_pointer(
seat.get_pointer().unwrap(),
self.sink.clone(),
self.store.clone(),
))
}
// destroy pointer if applicable
if !capabilities.contains(wl_seat::Capability::Pointer) {
if let Some(pointer) = self.pointer.take() {
if pointer.version() >= 3 {
use self::wl_pointer::RequestsTrait;
pointer.release();
}
}
}
// create keyboard if applicable
if capabilities.contains(wl_seat::Capability::Keyboard) && self.keyboard.is_none() {
self.keyboard = Some(super::keyboard::init_keyboard(
seat.get_keyboard().unwrap(),
self.sink.clone(),
))
}
// destroy keyboard if applicable
if !capabilities.contains(wl_seat::Capability::Keyboard) {
if let Some(kbd) = self.keyboard.take() {
if kbd.version() >= 3 {
use self::wl_keyboard::RequestsTrait;
kbd.release();
}
}
}
// create touch if applicable
if capabilities.contains(wl_seat::Capability::Touch) && self.touch.is_none() {
self.touch = Some(super::touch::implement_touch(
seat.get_touch().unwrap(),
self.sink.clone(),
self.store.clone(),
))
}
// destroy touch if applicable
if !capabilities.contains(wl_seat::Capability::Touch) {
if let Some(touch) = self.touch.take() {
if touch.version() >= 3 {
use self::wl_touch::RequestsTrait;
touch.release();
}
}
}
}
}
}
}
impl Drop for SeatData {
fn drop(&mut self) {
if let Some(pointer) = self.pointer.take() {
if pointer.version() >= 3 {
use self::wl_pointer::RequestsTrait;
pointer.release();
}
}
if let Some(kbd) = self.keyboard.take() {
if kbd.version() >= 3 {
use self::wl_keyboard::RequestsTrait;
kbd.release();
}
}
if let Some(touch) = self.touch.take() {
if touch.version() >= 3 {
use self::wl_touch::RequestsTrait;
touch.release();
}
}
}
}
/*
* Monitor stuff
*/
pub struct MonitorId {
pub(crate) proxy: Proxy<wl_output::WlOutput>,
pub(crate) mgr: OutputMgr,
}
impl Clone for MonitorId {
fn clone(&self) -> MonitorId {
MonitorId {
proxy: self.proxy.clone(),
mgr: self.mgr.clone(),
}
}
}
impl MonitorId {
pub fn get_name(&self) -> Option<String> {
self.mgr.with_info(&self.proxy, |_, info| {
format!("{} ({})", info.model, info.make)
})
}
#[inline]
pub fn get_native_identifier(&self) -> u32 {
self.mgr.with_info(&self.proxy, |id, _| id).unwrap_or(0)
}
pub fn get_dimensions(&self) -> (u32, u32) {
match self.mgr.with_info(&self.proxy, |_, info| {
info.modes
.iter()
.find(|m| m.is_current)
.map(|m| m.dimensions)
}) {
Some(Some((w, h))) => (w as u32, h as u32),
_ => (0, 0),
}
}
pub fn get_position(&self) -> (i32, i32) {
self.mgr
.with_info(&self.proxy, |_, info| info.location)
.unwrap_or((0, 0))
2017-03-05 00:04:01 +11:00
}
#[inline]
pub fn get_hidpi_factor(&self) -> f32 {
self.mgr
.with_info(&self.proxy, |_, info| info.scale_factor as f32)
.unwrap_or(1.0)
}
}