Skip to main content

mitsuami_linux/
wayland.rs

1//! Wayland: the subsurface, the pointer lock and the shortcuts inhibitor,
2//! on the toolkit's own connection.
3
4use std::ffi::c_void;
5use std::ptr::NonNull;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex};
8
9use mitsuami_core::raw_window_handle::{
10    HandleError, RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle,
11};
12use mitsuami_core::{NativeSurface, SurfaceHandle, SurfaceInput};
13use wayland_backend::client::{Backend, ObjectId};
14use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init};
15use wayland_client::protocol::{
16    wl_callback, wl_compositor, wl_pointer, wl_region, wl_registry, wl_seat, wl_subcompositor, wl_subsurface,
17    wl_surface,
18};
19use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, delegate_noop};
20use wayland_protocols::wp::keyboard_shortcuts_inhibit::zv1::client::{
21    zwp_keyboard_shortcuts_inhibit_manager_v1 as inhibit_manager, zwp_keyboard_shortcuts_inhibitor_v1 as inhibitor,
22};
23use wayland_protocols::wp::pointer_constraints::zv1::client::{
24    zwp_locked_pointer_v1 as locked_pointer, zwp_pointer_constraints_v1 as constraints,
25};
26use wayland_protocols::wp::relative_pointer::zv1::client::{
27    zwp_relative_pointer_manager_v1 as relative_manager, zwp_relative_pointer_v1 as relative_pointer,
28};
29use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
30
31use crate::{LockEvent, LockSink};
32
33/// A connection to the toolkit's display.
34///
35/// # Safety
36///
37/// `display` is the toolkit's live `wl_display`.
38unsafe fn connection(display: NonNull<c_void>) -> Connection {
39    // SAFETY: the caller's.
40    unsafe { Connection::from_backend(Backend::from_foreign_display(display.as_ptr().cast())) }
41}
42
43/// A proxy for a surface the toolkit made, on `conn`.
44///
45/// # Safety
46///
47/// `surface` is a live `wl_surface` on that connection.
48unsafe fn foreign_surface(conn: &Connection, surface: *mut c_void) -> Option<wl_surface::WlSurface> {
49    // SAFETY: the caller's.
50    let id = unsafe { ObjectId::from_ptr(wl_surface::WlSurface::interface(), surface.cast()) }.ok()?;
51    wl_surface::WlSurface::from_id(conn, id).ok()
52}
53
54/// A `wl_surface` of our own, and while shown the subsurface role that
55/// puts it over a window. Clones share it. Wayland proxies may be used from
56/// any thread; the backend uses it from its UI thread.
57#[derive(Clone)]
58pub struct Subsurface(Arc<Inner>);
59
60struct Globals;
61
62struct Inner {
63    conn: Connection,
64    /// The toolkit's `wl_display`, which the app's GPU API connects through.
65    display: NonNull<c_void>,
66    queue: Mutex<EventQueue<Globals>>,
67    subcompositor: wl_subcompositor::WlSubcompositor,
68    surface: wl_surface::WlSurface,
69    viewport: wp_viewport::WpViewport,
70    role: Mutex<Option<wl_subsurface::WlSubsurface>>,
71    /// Where it was put, in the window surface's logical coordinates.
72    placed: Mutex<Option<(i32, i32, i32, i32)>>,
73}
74
75// SAFETY: the display pointer is only handed out, never dereferenced here;
76// `wl_display` connections are thread-safe.
77unsafe impl Send for Inner {}
78unsafe impl Sync for Inner {}
79
80impl Subsurface {
81    /// A surface on the toolkit's connection, not shown yet.
82    ///
83    /// # Safety
84    ///
85    /// `display` is the toolkit's live `wl_display`, which stays connected
86    /// as long as the process uses it.
87    pub unsafe fn new(display: *mut c_void) -> Result<Subsurface, String> {
88        let display = NonNull::new(display).ok_or("no wl_display")?;
89        // SAFETY: the caller's.
90        let conn = unsafe { connection(display) };
91        let (globals, queue) = registry_queue_init::<Globals>(&conn).map_err(|e| e.to_string())?;
92        let qh = queue.handle();
93        let compositor: wl_compositor::WlCompositor =
94            globals.bind(&qh, 1..=4, ()).map_err(|e| format!("wl_compositor: {e}"))?;
95        let subcompositor: wl_subcompositor::WlSubcompositor =
96            globals.bind(&qh, 1..=1, ()).map_err(|e| format!("wl_subcompositor: {e}"))?;
97        let viewporter: wp_viewporter::WpViewporter =
98            globals.bind(&qh, 1..=1, ()).map_err(|e| format!("wp_viewporter: {e}"))?;
99        let surface = compositor.create_surface(&qh, ());
100        let region = compositor.create_region(&qh, ());
101        surface.set_input_region(Some(&region));
102        region.destroy();
103        let viewport = viewporter.get_viewport(&surface, &qh, ());
104        conn.flush().map_err(|e| e.to_string())?;
105        Ok(Subsurface(Arc::new(Inner {
106            conn,
107            display,
108            queue: Mutex::new(queue),
109            subcompositor,
110            surface,
111            viewport,
112            role: Mutex::new(None),
113            placed: Mutex::new(None),
114        })))
115    }
116
117    /// What the app gets: it keeps the surface alive.
118    pub fn handle(&self) -> SurfaceHandle {
119        SurfaceHandle::new(self.clone())
120    }
121
122    /// Puts the surface over `parent`, desync, so its commits show without
123    /// waiting for the window's. A window's surface is new each time the
124    /// window is mapped, so it's given each time.
125    ///
126    /// # Safety
127    ///
128    /// `parent` is a live `wl_surface` on the same connection.
129    pub unsafe fn attach(&self, parent: *mut c_void) {
130        self.detach();
131        // SAFETY: the caller's.
132        let Some(parent) = (unsafe { foreign_surface(&self.0.conn, parent) }) else { return };
133        let queue = self.0.queue.lock().unwrap();
134        let role = self.0.subcompositor.get_subsurface(&self.0.surface, &parent, &queue.handle(), ());
135        role.set_desync();
136        *self.0.role.lock().unwrap() = Some(role);
137        let _ = self.0.conn.flush();
138    }
139
140    /// Takes the surface off its window: without its role, it isn't shown.
141    pub fn detach(&self) {
142        *self.0.placed.lock().unwrap() = None;
143        if let Some(role) = self.0.role.lock().unwrap().take() {
144            role.destroy();
145            let _ = self.0.conn.flush();
146        }
147    }
148
149    /// Where it sits in the window's surface, and its size, in logical
150    /// pixels. Returns whether that changed: a move takes effect with the
151    /// window's next commit, so the backend then asks for a frame.
152    pub fn place(&self, x: i32, y: i32, width: i32, height: i32) -> bool {
153        // Events for our objects (outputs entered) are filed under our
154        // queue as the toolkit reads the socket; nothing needs them.
155        let _ = self.0.queue.lock().unwrap().dispatch_pending(&mut Globals);
156        let role = self.0.role.lock().unwrap();
157        let (Some(role), true) = (&*role, width > 0 && height > 0) else { return false };
158        let mut placed = self.0.placed.lock().unwrap();
159        if *placed == Some((x, y, width, height)) {
160            return false;
161        }
162        *placed = Some((x, y, width, height));
163        role.set_position(x, y);
164        self.0.viewport.set_destination(width, height);
165        let _ = self.0.conn.flush();
166        true
167    }
168}
169
170impl Drop for Inner {
171    fn drop(&mut self) {
172        if let Some(role) = self.role.get_mut().unwrap().take() {
173            role.destroy();
174        }
175        self.viewport.destroy();
176        self.surface.destroy();
177        let _ = self.conn.flush();
178    }
179}
180
181// SAFETY: it owns the surface and its display connection, destroyed only
182// when it's dropped.
183unsafe impl NativeSurface for Subsurface {
184    fn window_handle(&self) -> Result<RawWindowHandle, HandleError> {
185        let surface = NonNull::new(self.0.surface.id().as_ptr().cast()).ok_or(HandleError::Unavailable)?;
186        Ok(RawWindowHandle::Wayland(WaylandWindowHandle::new(surface)))
187    }
188
189    fn display_handle(&self) -> Result<RawDisplayHandle, HandleError> {
190        Ok(RawDisplayHandle::Wayland(WaylandDisplayHandle::new(self.0.display)))
191    }
192}
193
194impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for Globals {
195    fn event(
196        _: &mut Self,
197        _: &wl_registry::WlRegistry,
198        _: wl_registry::Event,
199        _: &GlobalListContents,
200        _: &Connection,
201        _: &QueueHandle<Self>,
202    ) {
203    }
204}
205
206delegate_noop!(Globals: ignore wl_compositor::WlCompositor);
207delegate_noop!(Globals: ignore wl_subcompositor::WlSubcompositor);
208delegate_noop!(Globals: ignore wl_surface::WlSurface);
209delegate_noop!(Globals: ignore wl_subsurface::WlSubsurface);
210delegate_noop!(Globals: ignore wl_region::WlRegion);
211delegate_noop!(Globals: ignore wp_viewporter::WpViewporter);
212delegate_noop!(Globals: ignore wp_viewport::WpViewport);
213
214// ------------------------------------------------------------- pointer lock
215
216/// The pointer held on a window's surface (`zwp_locked_pointer_v1`, for as
217/// long as the compositor keeps it), its moves reported as relative
218/// motion. The compositor locks it once the pointer is over the surface,
219/// and ends it as it sees fit (when the window loses focus): that's
220/// reported as [`LockEvent::Ended`]. Unlocked when dropped.
221///
222/// It uses a seat and a pointer of our own: the compositor sends a
223/// client's pointer events to each of its pointers.
224pub struct PointerLock {
225    listener: Listener,
226    locked: locked_pointer::ZwpLockedPointerV1,
227    relative: relative_pointer::ZwpRelativePointerV1,
228    pointer: wl_pointer::WlPointer,
229    seat: wl_seat::WlSeat,
230}
231
232impl PointerLock {
233    /// Locks the pointer on `surface`, the window's surface, whose input
234    /// region has the pointer.
235    ///
236    /// # Safety
237    ///
238    /// `display` is the toolkit's live `wl_display`, and `surface` a live
239    /// `wl_surface` on it.
240    pub unsafe fn new(display: *mut c_void, surface: *mut c_void, sink: LockSink) -> Result<PointerLock, String> {
241        let display = NonNull::new(display).ok_or("no wl_display")?;
242        // SAFETY: the caller's.
243        let conn = unsafe { connection(display) };
244        let (globals, queue) = registry_queue_init::<Watch>(&conn).map_err(|e| e.to_string())?;
245        let qh = queue.handle();
246        let seat = bind_seat(&globals, &qh)?;
247        let constraints: constraints::ZwpPointerConstraintsV1 =
248            globals.bind(&qh, 1..=1, ()).map_err(|e| format!("zwp_pointer_constraints_v1: {e}"))?;
249        let manager: relative_manager::ZwpRelativePointerManagerV1 =
250            globals.bind(&qh, 1..=1, ()).map_err(|e| format!("zwp_relative_pointer_manager_v1: {e}"))?;
251        // SAFETY: the caller's.
252        let surface = unsafe { foreign_surface(&conn, surface) }.ok_or("no wl_surface")?;
253        let pointer = seat.get_pointer(&qh, ());
254        let relative = manager.get_relative_pointer(&pointer, &qh, ());
255        let locked = constraints.lock_pointer(&surface, &pointer, None, constraints::Lifetime::Oneshot, &qh, ());
256        manager.destroy();
257        constraints.destroy();
258        conn.flush().map_err(|e| e.to_string())?;
259        let listener = Listener::start(conn, queue, sink);
260        Ok(PointerLock { listener, locked, relative, pointer, seat })
261    }
262}
263
264impl Drop for PointerLock {
265    fn drop(&mut self) {
266        self.locked.destroy();
267        self.relative.destroy();
268        if self.pointer.version() >= 3 {
269            self.pointer.release();
270        }
271        release_seat(&self.seat);
272        self.listener.stop();
273    }
274}
275
276// ---------------------------------------------------- shortcuts inhibitor
277
278/// The compositor's own shortcuts sent to a window as keys
279/// (`zwp_keyboard_shortcuts_inhibitor_v1`), while it has keyboard focus.
280/// The compositor may end it (it keeps a shortcut of its own to): that's
281/// reported as [`LockEvent::Ended`]. For toolkits without an API for it
282/// (Qt); GTK has `gdk_toplevel_inhibit_system_shortcuts`.
283pub struct ShortcutsInhibitor {
284    listener: Listener,
285    inhibitor: inhibitor::ZwpKeyboardShortcutsInhibitorV1,
286    seat: wl_seat::WlSeat,
287}
288
289impl ShortcutsInhibitor {
290    /// # Safety
291    ///
292    /// `display` is the toolkit's live `wl_display`, and `surface` a live
293    /// `wl_surface` on it.
294    pub unsafe fn new(
295        display: *mut c_void,
296        surface: *mut c_void,
297        sink: LockSink,
298    ) -> Result<ShortcutsInhibitor, String> {
299        let display = NonNull::new(display).ok_or("no wl_display")?;
300        // SAFETY: the caller's.
301        let conn = unsafe { connection(display) };
302        let (globals, queue) = registry_queue_init::<Watch>(&conn).map_err(|e| e.to_string())?;
303        let qh = queue.handle();
304        let seat = bind_seat(&globals, &qh)?;
305        let manager: inhibit_manager::ZwpKeyboardShortcutsInhibitManagerV1 =
306            globals.bind(&qh, 1..=1, ()).map_err(|e| format!("zwp_keyboard_shortcuts_inhibit_manager_v1: {e}"))?;
307        // SAFETY: the caller's.
308        let surface = unsafe { foreign_surface(&conn, surface) }.ok_or("no wl_surface")?;
309        let inhibitor = manager.inhibit_shortcuts(&surface, &seat, &qh, ());
310        manager.destroy();
311        conn.flush().map_err(|e| e.to_string())?;
312        let listener = Listener::start(conn, queue, sink);
313        Ok(ShortcutsInhibitor { listener, inhibitor, seat })
314    }
315}
316
317impl Drop for ShortcutsInhibitor {
318    fn drop(&mut self) {
319        self.inhibitor.destroy();
320        release_seat(&self.seat);
321        self.listener.stop();
322    }
323}
324
325/// The first seat: desktops have one.
326fn bind_seat(globals: &GlobalList, qh: &QueueHandle<Watch>) -> Result<wl_seat::WlSeat, String> {
327    globals.bind(qh, 1..=5, ()).map_err(|e| format!("wl_seat: {e}"))
328}
329
330fn release_seat(seat: &wl_seat::WlSeat) {
331    if seat.version() >= 5 {
332        seat.release();
333    }
334}
335
336/// Dispatches a lock's queue on a thread of its own, as the toolkit reads
337/// the connection (libwayland lets several threads read it), until it's
338/// stopped.
339struct Listener {
340    conn: Connection,
341    qh: QueueHandle<Watch>,
342    stopped: Arc<AtomicBool>,
343}
344
345/// What a lock's thread keeps.
346struct Watch {
347    sink: LockSink,
348    stopped: Arc<AtomicBool>,
349    locked: bool,
350}
351
352impl Watch {
353    fn report(&self, event: LockEvent) {
354        if !self.stopped.load(Ordering::Acquire) {
355            (self.sink)(event);
356        }
357    }
358}
359
360impl Listener {
361    fn start(conn: Connection, mut queue: EventQueue<Watch>, sink: LockSink) -> Listener {
362        let stopped = Arc::new(AtomicBool::new(false));
363        let qh = queue.handle();
364        let mut watch = Watch { sink, stopped: stopped.clone(), locked: false };
365        let spawned = std::thread::Builder::new().name("mitsuami-wayland-lock".into()).spawn(move || {
366            while !watch.stopped.load(Ordering::Acquire) {
367                if queue.blocking_dispatch(&mut watch).is_err() {
368                    break;
369                }
370            }
371        });
372        if let Err(problem) = spawned {
373            eprintln!("mitsuami: no thread for a pointer lock: {problem}");
374        }
375        Listener { conn, qh, stopped }
376    }
377
378    /// Stops reporting, and wakes the thread (a roundtrip's reply) so it
379    /// sees it and ends.
380    fn stop(&self) {
381        self.stopped.store(true, Ordering::Release);
382        self.conn.display().sync(&self.qh, ());
383        let _ = self.conn.flush();
384    }
385}
386
387impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for Watch {
388    fn event(
389        _: &mut Self,
390        _: &wl_registry::WlRegistry,
391        _: wl_registry::Event,
392        _: &GlobalListContents,
393        _: &Connection,
394        _: &QueueHandle<Self>,
395    ) {
396    }
397}
398
399impl Dispatch<locked_pointer::ZwpLockedPointerV1, ()> for Watch {
400    fn event(
401        watch: &mut Self,
402        _: &locked_pointer::ZwpLockedPointerV1,
403        event: locked_pointer::Event,
404        _: &(),
405        _: &Connection,
406        _: &QueueHandle<Self>,
407    ) {
408        match event {
409            locked_pointer::Event::Locked => watch.locked = true,
410            // A one-shot lock, once let go, is gone.
411            locked_pointer::Event::Unlocked => {
412                watch.locked = false;
413                watch.report(LockEvent::Ended);
414            }
415            _ => {}
416        }
417    }
418}
419
420impl Dispatch<relative_pointer::ZwpRelativePointerV1, ()> for Watch {
421    fn event(
422        watch: &mut Self,
423        _: &relative_pointer::ZwpRelativePointerV1,
424        event: relative_pointer::Event,
425        _: &(),
426        _: &Connection,
427        _: &QueueHandle<Self>,
428    ) {
429        // Accelerated, in the surface's logical pixels, and before the
430        // compositor's acceleration, in the device's counts; reported
431        // whenever the pointer moves over the app's surfaces, locked or not.
432        if let relative_pointer::Event::RelativeMotion { dx, dy, dx_unaccel, dy_unaccel, .. } = event
433            && watch.locked
434        {
435            watch.report(LockEvent::Input(SurfaceInput::Motion { dx: dx as f32, dy: dy as f32 }));
436            let (dx, dy) = (dx_unaccel as f32, dy_unaccel as f32);
437            watch.report(LockEvent::Input(SurfaceInput::RawMotion { dx, dy }));
438        }
439    }
440}
441
442impl Dispatch<inhibitor::ZwpKeyboardShortcutsInhibitorV1, ()> for Watch {
443    fn event(
444        watch: &mut Self,
445        _: &inhibitor::ZwpKeyboardShortcutsInhibitorV1,
446        event: inhibitor::Event,
447        _: &(),
448        _: &Connection,
449        _: &QueueHandle<Self>,
450    ) {
451        if let inhibitor::Event::Inactive = event {
452            watch.report(LockEvent::Ended);
453        }
454    }
455}
456
457delegate_noop!(Watch: ignore wl_seat::WlSeat);
458delegate_noop!(Watch: ignore wl_pointer::WlPointer);
459delegate_noop!(Watch: ignore wl_callback::WlCallback);
460delegate_noop!(Watch: ignore wl_surface::WlSurface);
461delegate_noop!(Watch: constraints::ZwpPointerConstraintsV1);
462delegate_noop!(Watch: relative_manager::ZwpRelativePointerManagerV1);
463delegate_noop!(Watch: inhibit_manager::ZwpKeyboardShortcutsInhibitManagerV1);