pub(crate) mod dnd;
pub(crate) mod io;
pub(crate) mod serials;
use std::any::Any;
use std::os::fd::{AsFd, AsRawFd, OwnedFd};
use std::sync::{Arc, Mutex, OnceLock};
use wayland_backend::client::WaylandError;
use wayland_backend::sys::client::Backend;
use wayland_client::globals::{GlobalListContents, registry_queue_init};
use wayland_client::protocol::wl_callback::{Event as CallbackEvent, WlCallback};
use wayland_client::protocol::wl_data_device::{Event as DataDeviceEvent, WlDataDevice};
use wayland_client::protocol::wl_data_device_manager::WlDataDeviceManager;
use wayland_client::protocol::wl_data_offer::{Event as DataOfferEvent, WlDataOffer};
use wayland_client::protocol::wl_data_source::{Event as DataSourceEvent, WlDataSource};
use wayland_client::protocol::wl_keyboard::{Event as KeyboardEvent, KeyState, WlKeyboard};
use wayland_client::protocol::wl_pointer::{ButtonState, Event as PointerEvent, WlPointer};
use wayland_client::protocol::wl_registry::WlRegistry;
use wayland_client::protocol::wl_seat::{Capability, Event as SeatEvent, WlSeat};
use wayland_client::protocol::wl_touch::{Event as TouchEvent, WlTouch};
use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum};
use crate::external_dnd::TouchSerialSource;
use serials::InputSerials;
pub(crate) type OfferMimes = Arc<Mutex<Vec<String>>>;
pub(crate) fn offer_mimes(offer: &WlDataOffer) -> Vec<String> {
offer
.data::<OfferMimes>()
.and_then(|mimes| mimes.lock().ok().map(|m| m.clone()))
.unwrap_or_default()
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SourceKind {
Selection,
Drag,
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
pub(crate) type Payload = Vec<(String, Arc<[u8]>)>;
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
struct OwnSelection {
source: WlDataSource,
payload: Payload,
owner_data: Arc<dyn Any + Send + Sync>,
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
struct SelectionCheck {
source: WlDataSource,
previous: Option<WlDataSource>,
announced: bool,
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
const MAX_OWNED_SOURCES: usize = 8;
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
pub(crate) enum SelectionView {
Own(Arc<dyn Any + Send + Sync>),
Foreign(Vec<String>),
Empty,
}
pub(crate) struct HubState {
conn: Connection,
qh: QueueHandle<HubState>,
manager: WlDataDeviceManager,
device: WlDataDevice,
_seat: WlSeat,
keyboard: Option<WlKeyboard>,
pointer: Option<WlPointer>,
touch: Option<WlTouch>,
serials: InputSerials,
pub(crate) press_serials: TouchSerialSource,
selection_offer: Option<WlDataOffer>,
owned: Vec<OwnSelection>,
checks: Vec<SelectionCheck>,
pub(crate) dnd: dnd::DndState,
}
impl HubState {
pub(crate) fn conn(&self) -> &Connection {
&self.conn
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
pub(crate) fn selection(&self) -> SelectionView {
if let Some(own) = self.owned.last() {
return SelectionView::Own(own.owner_data.clone());
}
match &self.selection_offer {
Some(offer) => SelectionView::Foreign(offer_mimes(offer)),
None => SelectionView::Empty,
}
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
pub(crate) fn selection_offer_id(&self) -> Option<wayland_client::backend::ObjectId> {
self.selection_offer.as_ref().map(Proxy::id)
}
#[cfg(all(test, feature = "clipboard"))]
pub(crate) fn has_keyboard_focus(&self) -> bool {
self.serials.has_keyboard_focus()
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
pub(crate) fn set_selection(
&mut self,
payload: Payload,
owner_data: Arc<dyn Any + Send + Sync>,
) -> Result<(), String> {
let serial = self
.serials
.for_selection()
.map_err(|err| format!("the Wayland clipboard cannot be set: {err}"))?;
let source = self
.manager
.create_data_source(&self.qh, SourceKind::Selection);
for (mime, _) in &payload {
source.offer(mime.clone());
}
self.device.set_selection(Some(&source), serial);
self.conn.display().sync(&self.qh, source.clone());
self.checks.push(SelectionCheck {
source: source.clone(),
previous: self.owned.last().map(|own| own.source.clone()),
announced: false,
});
if self.owned.len() == MAX_OWNED_SOURCES {
self.owned.remove(0).source.destroy();
}
self.owned.push(OwnSelection {
source,
payload,
owner_data,
});
Ok(())
}
fn selection_checked(&mut self, source: &WlDataSource) {
let Some(at) = self.checks.iter().position(|c| &c.source == source) else {
return;
};
let check = self.checks.remove(at);
let previous_kept = check
.previous
.as_ref()
.is_some_and(|previous| self.owned.iter().any(|own| &own.source == previous));
if check.announced || !previous_kept {
return;
}
if let Some(at) = self.owned.iter().position(|own| own.source == check.source) {
self.owned.remove(at);
check.source.destroy();
eprintln!(
"teksilo-platform: the compositor ignored a copy (no input since the previous one?); the clipboard keeps what was copied before"
);
}
}
#[cfg_attr(
not(feature = "clipboard"),
allow(
dead_code,
reason = "the clipboard half of the hub, used when the `clipboard` feature is on"
)
)]
pub(crate) fn receive_selection(&mut self, mime: &str) -> Result<OwnedFd, String> {
let offer = self
.selection_offer
.as_ref()
.ok_or_else(|| "the clipboard is empty".to_string())?;
let (read, write) = io::pipe().map_err(|err| format!("cannot create a pipe: {err}"))?;
offer.receive(mime.to_string(), write.as_fd());
match self.conn.flush() {
Ok(()) => {}
Err(WaylandError::Io(io)) if io.kind() == std::io::ErrorKind::WouldBlock => {}
Err(err) => return Err(format!("cannot reach the compositor: {err}")),
}
drop(write);
Ok(read)
}
fn serve_selection(&self, source: &WlDataSource, mime: &str, fd: OwnedFd) {
let Some(own) = self.owned.iter().find(|own| &own.source == source) else {
return;
};
let Some((_, bytes)) = own.payload.iter().find(|(m, _)| m == mime) else {
return;
};
io::serve_in_background(fd, bytes.clone(), format!("the clipboard as {mime}"));
}
}
struct HubInner {
queue: EventQueue<HubState>,
state: HubState,
}
pub(crate) struct WaylandDataHub {
conn: Connection,
inner: Mutex<HubInner>,
display: usize,
#[cfg_attr(
not(all(test, feature = "clipboard")),
allow(dead_code, reason = "only the compositor tests stop a hub")
)]
stop_write: OwnedFd,
_keepalive: Box<dyn Any + Send + Sync>,
}
#[derive(Default)]
struct Registry {
hubs: Vec<Arc<WaylandDataHub>>,
failed: Vec<(usize, String)>,
}
fn registry() -> &'static Mutex<Registry> {
static HUBS: OnceLock<Mutex<Registry>> = OnceLock::new();
HUBS.get_or_init(Mutex::default)
}
impl WaylandDataHub {
pub(crate) fn for_display(
display: &winit::event_loop::OwnedDisplayHandle,
) -> Result<Arc<Self>, String> {
use raw_window_handle::{HasDisplayHandle, RawDisplayHandle};
let raw = display
.display_handle()
.map_err(|err| format!("no display handle: {err}"))?
.as_raw();
let RawDisplayHandle::Wayland(wayland) = raw else {
return Err("the display is not a Wayland display".into());
};
let ptr = wayland.display.as_ptr();
let mut registry = registry()
.lock()
.map_err(|_| "the Wayland data registry is poisoned".to_string())?;
if let Some(hub) = registry.hubs.iter().find(|hub| hub.display == ptr as usize) {
return Ok(hub.clone());
}
if let Some((_, why)) = registry.failed.iter().find(|(d, _)| *d == ptr as usize) {
return Err(why.clone());
}
let backend = unsafe { Backend::from_foreign_display(ptr.cast()) };
let conn = Connection::from_backend(backend);
match Self::start(conn, ptr as usize, Box::new(display.clone())) {
Ok(hub) => {
registry.hubs.push(hub.clone());
Ok(hub)
}
Err(why) => {
registry.failed.push((ptr as usize, why.clone()));
Err(why)
}
}
}
pub(crate) fn existing(ptr: usize) -> Option<Arc<Self>> {
registry()
.lock()
.ok()?
.hubs
.iter()
.find(|hub| hub.display == ptr)
.cloned()
}
#[cfg(all(test, feature = "clipboard"))]
pub(crate) fn for_connection(conn: Connection) -> Result<Arc<Self>, String> {
let display = conn.backend().display_ptr() as usize;
Self::start(conn.clone(), display, Box::new(conn))
}
fn start(
conn: Connection,
display: usize,
keepalive: Box<dyn Any + Send + Sync>,
) -> Result<Arc<Self>, String> {
let (globals, mut queue) = registry_queue_init::<HubState>(&conn)
.map_err(|err| format!("cannot read the compositor's globals: {err}"))?;
let qh = queue.handle();
let seat = globals
.bind::<WlSeat, _, _>(&qh, 1..=5, ())
.map_err(|err| format!("the compositor offers no seat: {err}"))?;
let manager = match globals.bind::<WlDataDeviceManager, _, _>(&qh, 1..=3, ()) {
Ok(manager) => manager,
Err(err) => {
if seat.version() >= 5 {
seat.release();
let _ = conn.flush();
}
return Err(format!(
"the compositor offers no data device manager: {err}"
));
}
};
let device = manager.get_data_device(&seat, &qh, ());
let mut state = HubState {
conn: conn.clone(),
qh,
manager,
device,
_seat: seat,
keyboard: None,
pointer: None,
touch: None,
serials: InputSerials::default(),
press_serials: TouchSerialSource::default(),
selection_offer: None,
owned: Vec::new(),
checks: Vec::new(),
dnd: dnd::DndState::default(),
};
queue
.roundtrip(&mut state)
.map_err(|err| format!("the compositor did not answer: {err}"))?;
let (stop_read, stop_write) =
io::pipe().map_err(|err| format!("cannot create a pipe: {err}"))?;
let hub = Arc::new(Self {
conn,
inner: Mutex::new(HubInner { queue, state }),
display,
stop_write,
_keepalive: keepalive,
});
let for_thread = hub.clone();
std::thread::Builder::new()
.name("teksilo-wayland-data".into())
.spawn(move || for_thread.run(stop_read))
.map_err(|err| format!("cannot start the Wayland data thread: {err}"))?;
Ok(hub)
}
pub(crate) fn with_state<R>(&self, f: impl FnOnce(&mut HubState) -> R) -> Result<R, String> {
let mut inner = self
.inner
.lock()
.map_err(|_| "the Wayland data state is poisoned".to_string())?;
let HubInner { queue, state } = &mut *inner;
queue
.dispatch_pending(state)
.map_err(|err| format!("the Wayland connection failed: {err}"))?;
let result = f(state);
let _ = self.conn.flush();
Ok(result)
}
#[cfg(all(test, feature = "clipboard"))]
pub(crate) fn shutdown(&self) {
let one = [1u8];
let _ = unsafe { libc::write(self.stop_write.as_raw_fd(), one.as_ptr().cast(), 1) };
}
fn run(self: Arc<Self>, stop_read: OwnedFd) {
loop {
let guard = {
let Ok(mut inner) = self.inner.lock() else {
eprintln!(
"teksilo-platform: the Wayland data state is poisoned; clipboard and drag-and-drop stop"
);
return;
};
let HubInner { queue, state } = &mut *inner;
if let Err(err) = queue.dispatch_pending(state) {
eprintln!(
"teksilo-platform: the Wayland connection failed ({err}); clipboard and drag-and-drop stop"
);
return;
}
let _ = self.conn.flush();
queue.prepare_read()
};
let Some(guard) = guard else { continue };
let mut fds = [
libc::pollfd {
fd: guard.connection_fd().as_raw_fd(),
events: libc::POLLIN,
revents: 0,
},
libc::pollfd {
fd: stop_read.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
},
];
let ready = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
if ready < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
continue;
}
if matches!(err.raw_os_error(), Some(libc::ENOMEM | libc::EAGAIN)) {
drop(guard);
std::thread::sleep(std::time::Duration::from_millis(50));
continue;
}
eprintln!(
"teksilo-platform: waiting on the Wayland connection failed ({err}); clipboard and drag-and-drop stop"
);
return;
}
if fds[1].revents != 0 {
return;
}
if let Err(err) = guard.read() {
match err {
wayland_backend::client::WaylandError::Io(io)
if io.kind() == std::io::ErrorKind::WouldBlock => {}
other => {
eprintln!(
"teksilo-platform: reading the Wayland connection failed ({other}); clipboard and drag-and-drop stop"
);
return;
}
}
}
}
}
}
impl Dispatch<WlRegistry, GlobalListContents> for HubState {
fn event(
_: &mut Self,
_: &WlRegistry,
_: <WlRegistry as Proxy>::Event,
_: &GlobalListContents,
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<WlDataDeviceManager, ()> for HubState {
fn event(
_: &mut Self,
_: &WlDataDeviceManager,
_: <WlDataDeviceManager as Proxy>::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<WlSeat, ()> for HubState {
fn event(
state: &mut Self,
seat: &WlSeat,
event: SeatEvent,
_: &(),
_: &Connection,
qh: &QueueHandle<Self>,
) {
let SeatEvent::Capabilities {
capabilities: WEnum::Value(capabilities),
} = event
else {
return;
};
if capabilities.contains(Capability::Keyboard) {
if state.keyboard.is_none() {
state.keyboard = Some(seat.get_keyboard(qh, ()));
state.serials.set_keyboard_bound(true);
}
} else if let Some(keyboard) = state.keyboard.take() {
if keyboard.version() >= 3 {
keyboard.release();
}
state.serials.set_keyboard_bound(false);
}
if capabilities.contains(Capability::Pointer) {
if state.pointer.is_none() {
state.pointer = Some(seat.get_pointer(qh, ()));
}
} else if let Some(pointer) = state.pointer.take()
&& pointer.version() >= 3
{
pointer.release();
}
if capabilities.contains(Capability::Touch) {
if state.touch.is_none() {
state.touch = Some(seat.get_touch(qh, ()));
}
} else if let Some(touch) = state.touch.take()
&& touch.version() >= 3
{
touch.release();
}
}
}
impl Dispatch<WlKeyboard, ()> for HubState {
fn event(
state: &mut Self,
_: &WlKeyboard,
event: KeyboardEvent,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
KeyboardEvent::Enter { serial, .. } => state.serials.keyboard_enter(serial),
KeyboardEvent::Leave { .. } => state.serials.keyboard_leave(),
KeyboardEvent::Key {
serial,
state: key_state,
..
} => {
if matches!(
key_state,
WEnum::Value(KeyState::Pressed | KeyState::Released)
) {
state.serials.record(serial);
}
}
_ => {}
}
}
}
impl Dispatch<WlPointer, ()> for HubState {
fn event(
state: &mut Self,
_: &WlPointer,
event: PointerEvent,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
PointerEvent::Button {
serial, state: btn, ..
} => {
state.serials.record(serial);
if btn == WEnum::Value(ButtonState::Pressed) {
state.press_serials.record_pointer(serial);
} else {
state.press_serials.record_pointer_release();
dnd::release_reached_us(state, false);
}
}
PointerEvent::Enter { .. } | PointerEvent::Leave { .. } => {
state.press_serials.record_pointer_focus_change();
}
_ => {}
}
}
}
impl Dispatch<WlTouch, ()> for HubState {
fn event(
state: &mut Self,
_: &WlTouch,
event: TouchEvent,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
TouchEvent::Down { serial, .. } => {
state.serials.record(serial);
state.press_serials.record_touch(serial);
}
TouchEvent::Up { .. } => {
state.press_serials.record_touch_up();
dnd::release_reached_us(state, true);
}
TouchEvent::Cancel => state.press_serials.record_touch_cancel(),
_ => {}
}
}
}
impl Dispatch<WlDataOffer, OfferMimes> for HubState {
fn event(
_: &mut Self,
_: &WlDataOffer,
event: DataOfferEvent,
mimes: &OfferMimes,
_: &Connection,
_: &QueueHandle<Self>,
) {
if let DataOfferEvent::Offer { mime_type } = event
&& let Ok(mut mimes) = mimes.lock()
{
mimes.push(mime_type);
}
}
}
impl Dispatch<WlDataSource, SourceKind> for HubState {
fn event(
state: &mut Self,
source: &WlDataSource,
event: DataSourceEvent,
kind: &SourceKind,
_: &Connection,
_: &QueueHandle<Self>,
) {
match kind {
SourceKind::Selection => match event {
DataSourceEvent::Send { mime_type, fd } => {
state.serve_selection(source, &mime_type, fd);
}
DataSourceEvent::Cancelled => {
state.owned.retain(|own| &own.source != source);
source.destroy();
}
_ => {}
},
SourceKind::Drag => dnd::source_event(state, source, event),
}
}
}
impl Dispatch<WlCallback, WlDataSource> for HubState {
fn event(
state: &mut Self,
_: &WlCallback,
event: CallbackEvent,
source: &WlDataSource,
_: &Connection,
_: &QueueHandle<Self>,
) {
if let CallbackEvent::Done { .. } = event {
state.selection_checked(source);
}
}
}
impl Dispatch<WlDataDevice, ()> for HubState {
fn event(
state: &mut Self,
_: &WlDataDevice,
event: DataDeviceEvent,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
DataDeviceEvent::DataOffer { .. } => {}
DataDeviceEvent::Selection { id } => {
if let Some(oldest) = state.checks.first_mut() {
oldest.announced = true;
}
if let Some(previous) = state.selection_offer.take()
&& id.as_ref() != Some(&previous)
{
previous.destroy();
}
state.selection_offer = id;
}
other => dnd::device_event(state, other),
}
}
wayland_client::event_created_child!(HubState, WlDataDevice, [
wayland_client::protocol::wl_data_device::EVT_DATA_OFFER_OPCODE => (WlDataOffer, OfferMimes::default()),
]);
}