Skip to main content

mitsuami_linux/
x11.rs

1//! X11: a child window of the toolkit's window, on an xcb connection of
2//! our own, and the pointer lock, a pointer grab on it, with XInput 2's
3//! raw motion for the mouse's moves before the server's acceleration.
4
5use std::ffi::CString;
6use std::num::NonZeroU32;
7use std::ptr::NonNull;
8use std::sync::atomic::{AtomicU32, Ordering};
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11
12use mitsuami_core::raw_window_handle::{
13    HandleError, RawDisplayHandle, RawWindowHandle, XcbDisplayHandle, XcbWindowHandle,
14};
15use mitsuami_core::{Modifiers, MouseButton, NativeSurface, Point, ScrollDelta, SurfaceHandle, SurfaceInput};
16use x11rb::connection::{Connection as _, RequestConnection as _};
17use x11rb::protocol::Event;
18use x11rb::protocol::shape::{self, ConnectionExt as _};
19use x11rb::protocol::xinput::{self, ConnectionExt as _};
20use x11rb::protocol::xproto::{
21    AtomEnum, ButtonPressEvent, ChangeWindowAttributesAux, ClientMessageEvent, ConfigureWindowAux, ConnectionExt as _,
22    CreateWindowAux, EventMask, GrabMode, GrabStatus, Gravity, KeyButMask, NotifyMode, StackMode, WindowClass,
23};
24use x11rb::xcb_ffi::XCBConnection;
25
26use crate::{LockEvent, LockSink};
27
28/// A window of our own, a child of the toolkit's window, over the widget.
29/// It takes no input (an empty input shape), so the pointer goes to the
30/// toolkit's window under it. Clones share it; xcb connections are
31/// thread-safe, so it may be used, and dropped, from any thread.
32#[derive(Clone)]
33pub struct ChildWindow(Arc<Inner>);
34
35struct Inner {
36    conn: XCBConnection,
37    screen: usize,
38    root: u32,
39    window: u32,
40    /// The toolkit's window it's in, while shown.
41    parent: Mutex<Option<u32>>,
42    /// Where it was put in its parent, in pixels; `None` while hidden.
43    placed: Mutex<Option<(i32, i32, u32, u32)>>,
44    /// The pointer lock in effect, by its number; 0 for none.
45    lock: AtomicU32,
46    locks: AtomicU32,
47    /// Lock threads reading the connection's events. A new lock's thread
48    /// waits for an earlier one to see its wake and end: xcb hands each
49    /// event to one of the threads waiting, so two would take each
50    /// other's.
51    readers: AtomicU32,
52}
53
54impl ChildWindow {
55    /// A window in `parent` (the toolkit's window, by its XID) on the
56    /// display the toolkit uses, not shown yet.
57    pub fn new(display_name: Option<&str>, parent: u32) -> Result<ChildWindow, String> {
58        let name = display_name.map(CString::new).transpose().map_err(|e| e.to_string())?;
59        let (conn, screen) = XCBConnection::connect(name.as_deref()).map_err(|e| e.to_string())?;
60        let root = conn.setup().roots[screen].root;
61        let window = conn.generate_id().map_err(|e| e.to_string())?;
62        // No background: until the app presents, what was there shows.
63        let aux = CreateWindowAux::new().background_pixmap(x11rb::NONE).bit_gravity(Gravity::NORTH_WEST);
64        conn.create_window(0, window, parent, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, 0, &aux)
65            .map_err(|e| e.to_string())?;
66        if conn.extension_information(shape::X11_EXTENSION_NAME).ok().flatten().is_some() {
67            let _ = conn.shape_rectangles(
68                shape::SO::SET,
69                shape::SK::INPUT,
70                x11rb::protocol::xproto::ClipOrdering::UNSORTED,
71                window,
72                0,
73                0,
74                &[],
75            );
76        }
77        conn.flush().map_err(|e| e.to_string())?;
78        Ok(ChildWindow(Arc::new(Inner {
79            conn,
80            screen,
81            root,
82            window,
83            parent: Mutex::new(Some(parent)),
84            placed: Mutex::new(None),
85            lock: AtomicU32::new(0),
86            locks: AtomicU32::new(0),
87            readers: AtomicU32::new(0),
88        })))
89    }
90
91    /// What the app gets: it keeps the window alive.
92    pub fn handle(&self) -> SurfaceHandle {
93        SurfaceHandle::new(self.clone())
94    }
95
96    /// Puts it in `parent`, the toolkit's window, if it's elsewhere;
97    /// hidden until it's placed.
98    pub fn attach(&self, parent: u32) {
99        let mut current = self.0.parent.lock().unwrap();
100        if *current != Some(parent) {
101            *self.0.placed.lock().unwrap() = None;
102            let _ = self.0.conn.unmap_window(self.0.window);
103            let _ = self.0.conn.reparent_window(self.0.window, parent, 0, 0);
104            *current = Some(parent);
105            let _ = self.0.conn.flush();
106        }
107        self.0.drain();
108    }
109
110    /// Hides it, and takes it out of the toolkit's window, which would
111    /// destroy it with itself: the app may still present to it.
112    pub fn detach(&self) {
113        *self.0.placed.lock().unwrap() = None;
114        let mut parent = self.0.parent.lock().unwrap();
115        let _ = self.0.conn.unmap_window(self.0.window);
116        if parent.take().is_some() {
117            let _ = self.0.conn.reparent_window(self.0.window, self.0.root, 0, 0);
118        }
119        let _ = self.0.conn.flush();
120        self.0.drain();
121    }
122
123    /// Where it sits in its parent, and its size, in pixels: hidden while
124    /// it has no size. Returns whether that changed.
125    pub fn place(&self, x: i32, y: i32, width: i32, height: i32) -> bool {
126        if self.0.parent.lock().unwrap().is_none() {
127            return false;
128        }
129        let at = (width > 0 && height > 0).then_some((x, y, width as u32, height as u32));
130        let mut placed = self.0.placed.lock().unwrap();
131        if *placed == at {
132            return false;
133        }
134        let shown = placed.is_some();
135        *placed = at;
136        let conn = &self.0.conn;
137        match at {
138            Some((x, y, width, height)) => {
139                let aux = ConfigureWindowAux::new().x(x).y(y).width(width).height(height).stack_mode(StackMode::ABOVE);
140                let _ = conn.configure_window(self.0.window, &aux);
141                if !shown {
142                    let _ = conn.map_window(self.0.window);
143                }
144            }
145            None => {
146                let _ = conn.unmap_window(self.0.window);
147            }
148        }
149        let _ = conn.flush();
150        drop(placed);
151        self.0.drain();
152        true
153    }
154
155    /// Grabs the pointer on the window: the cursor hidden, held in the
156    /// window's middle, and its moves reported (in points, at `scale`
157    /// pixels to a point), with its buttons and wheel, which the grab
158    /// takes from the toolkit. A click that asked for it holds the
159    /// toolkit's grab until its button is let go, so it's tried until
160    /// then. Released when dropped.
161    pub fn lock_pointer(&self, scale: f32, sink: LockSink) -> PointerLock {
162        let number = self.0.locks.fetch_add(1, Ordering::Relaxed) + 1;
163        self.0.lock.store(number, Ordering::Release);
164        let inner = self.0.clone();
165        let spawned = std::thread::Builder::new()
166            .name("mitsuami-x11-lock".into())
167            .spawn(move || inner.hold_pointer(number, scale.max(1.0), sink));
168        if let Err(problem) = spawned {
169            eprintln!("mitsuami: no thread for a pointer lock: {problem}");
170        }
171        PointerLock { surface: self.clone(), number }
172    }
173}
174
175impl Inner {
176    fn locked(&self, number: u32) -> bool {
177        self.lock.load(Ordering::Acquire) == number
178    }
179
180    /// Reads what came on the connection while no lock thread reads it:
181    /// the errors of requests sent without waiting for a reply (a parent
182    /// gone before its child was placed), and a lock's events and wake
183    /// after it ended. xcb would keep them all. Not while a lock is in
184    /// effect, or a thread may still read: they'd take its events.
185    fn drain(&self) {
186        if self.lock.load(Ordering::Acquire) == 0 && self.readers.load(Ordering::Acquire) == 0 {
187            while let Ok(Some(_)) = self.conn.poll_for_event() {}
188        }
189    }
190
191    /// Selects what tells a lock its grab is gone: the server lets a grab
192    /// go when its window can't be seen (it, or the toolkit's window, is
193    /// unmapped), and a grab's end is a leave of mode `Ungrab` from its
194    /// window to the one the pointer is in. Without the shape extension
195    /// the window takes input, the pointer is in it and there's no leave,
196    /// so its unmapping is watched too.
197    /// Turned off before an ungrab of our own, whose leave isn't a loss.
198    fn watch_grab(&self, on: bool) {
199        let mask = if on { EventMask::LEAVE_WINDOW | EventMask::STRUCTURE_NOTIFY } else { EventMask::NO_EVENT };
200        let _ = self.conn.change_window_attributes(self.window, &ChangeWindowAttributesAux::new().event_mask(mask));
201    }
202
203    /// The middle of the window, in its own pixels.
204    fn middle(&self) -> Option<(i16, i16)> {
205        let (_, _, width, height) = (*self.placed.lock().unwrap())?;
206        Some(((width / 2) as i16, (height / 2) as i16))
207    }
208
209    /// A lock's thread: grabs, then reports until the lock is dropped.
210    fn hold_pointer(&self, number: u32, scale: f32, sink: LockSink) {
211        // An earlier lock's thread ends at its wake, which it's the only
212        // one reading. Not for long: a lock dropped wakes its thread.
213        let waited = Instant::now();
214        while self.readers.load(Ordering::Acquire) > 0 && waited.elapsed() < Duration::from_secs(1) {
215            std::thread::sleep(Duration::from_millis(5));
216        }
217        let cursor = match self.blank_cursor() {
218            Ok(cursor) => cursor,
219            Err(_) => return sink(LockEvent::Ended),
220        };
221        let mask = EventMask::POINTER_MOTION | EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE;
222        let started = Instant::now();
223        loop {
224            if !self.locked(number) {
225                let _ = self.conn.free_cursor(cursor);
226                let _ = self.conn.flush();
227                return;
228            }
229            let window = self.window;
230            let grabbed = self
231                .conn
232                .grab_pointer(
233                    false,
234                    window,
235                    mask,
236                    GrabMode::ASYNC,
237                    GrabMode::ASYNC,
238                    window,
239                    cursor,
240                    x11rb::CURRENT_TIME,
241                )
242                .ok()
243                .and_then(|cookie| cookie.reply().ok())
244                .map(|reply| reply.status);
245            match grabbed {
246                Some(GrabStatus::SUCCESS) => break,
247                Some(GrabStatus::ALREADY_GRABBED | GrabStatus::FROZEN)
248                    if started.elapsed() < Duration::from_secs(2) =>
249                {
250                    std::thread::sleep(Duration::from_millis(20));
251                }
252                _ => {
253                    let _ = self.conn.free_cursor(cursor);
254                    let _ = self.conn.flush();
255                    return sink(LockEvent::Ended);
256                }
257            }
258        }
259        // Counted before the lock is looked at again, so a newer lock's
260        // thread either waits for this one or this one sees it's dropped.
261        self.readers.fetch_add(1, Ordering::AcqRel);
262        self.watch_grab(true);
263        let _ = self.conn.free_cursor(cursor);
264        let raw = self.select_raw_motion(true);
265        // Dropped while the grab was on its way: the drop's ungrab may have
266        // come first, and the grab would stay with no one reading it.
267        if !self.locked(number) {
268            self.readers.fetch_sub(1, Ordering::AcqRel);
269            return self.let_go();
270        }
271        if !raw {
272            eprintln!("mitsuami: no XInput 2 on this X server: no raw motion while the pointer is locked");
273        }
274        self.warp_to_middle();
275        self.report(number, scale, &sink);
276        self.readers.fetch_sub(1, Ordering::AcqRel);
277        if !self.locked(number) {
278            self.let_go();
279        }
280    }
281
282    /// Lets the grab and raw motion go once no lock wants them: a newer
283    /// lock keeps them, as its own.
284    fn let_go(&self) {
285        if self.lock.load(Ordering::Acquire) == 0 {
286            self.watch_grab(false);
287            let _ = self.conn.ungrab_pointer(x11rb::CURRENT_TIME);
288            self.select_raw_motion(false);
289            let _ = self.conn.flush();
290        }
291    }
292
293    /// Reports the grab's events until the lock is dropped, or the server
294    /// lets the grab go. An earlier lock's wake, left unread, is just
295    /// another event, as are errors.
296    fn report(&self, number: u32, scale: f32, sink: &LockSink) {
297        let point = |x: i16, y: i16| Point::new(x as f32 / scale, y as f32 / scale);
298        loop {
299            let Ok(event) = self.conn.wait_for_event() else { return };
300            if !self.locked(number) {
301                return;
302            }
303            match event {
304                Event::MotionNotify(motion) => {
305                    let Some((mx, my)) = self.middle() else { continue };
306                    let (dx, dy) = (motion.event_x - mx, motion.event_y - my);
307                    // The warp back to the middle comes as a move too.
308                    if dx != 0 || dy != 0 {
309                        let (dx, dy) = (dx as f32 / scale, dy as f32 / scale);
310                        sink(LockEvent::Input(SurfaceInput::Motion { dx, dy }));
311                        self.warp_to_middle();
312                    }
313                }
314                Event::XinputRawMotion(raw) => {
315                    if let Some((dx, dy)) = raw_motion(&raw) {
316                        sink(LockEvent::Input(SurfaceInput::RawMotion { dx, dy }));
317                    }
318                }
319                Event::ButtonPress(press) => {
320                    if let Some(input) = button_input(&press, true, point) {
321                        sink(LockEvent::Input(input));
322                    }
323                }
324                Event::ButtonRelease(release) => {
325                    if let Some(input) = button_input(&release, false, point) {
326                        sink(LockEvent::Input(input));
327                    }
328                }
329                Event::LeaveNotify(leave) if leave.mode == NotifyMode::UNGRAB && leave.event == self.window => {
330                    return self.lost(sink);
331                }
332                Event::UnmapNotify(unmap) if unmap.window == self.window => return self.lost(sink),
333                _ => {}
334            }
335        }
336    }
337
338    /// The server let the grab go: what went with it is let go too, while
339    /// this thread is still counted, so a newer lock's grab comes after.
340    /// The lock stays in effect until the app lets go of it.
341    fn lost(&self, sink: &LockSink) {
342        self.watch_grab(false);
343        let _ = self.conn.ungrab_pointer(x11rb::CURRENT_TIME);
344        self.select_raw_motion(false);
345        let _ = self.conn.flush();
346        sink(LockEvent::Ended);
347    }
348
349    /// Raw motion comes only to the root window, and to a client that
350    /// said it speaks XInput 2. Returns whether it's selected (or, turning
351    /// it off, was asked to be unselected).
352    fn select_raw_motion(&self, on: bool) -> bool {
353        if self.conn.extension_information(xinput::X11_EXTENSION_NAME).ok().flatten().is_none() {
354            return false;
355        }
356        if on {
357            let version = self.conn.xinput_xi_query_version(2, 0).ok().and_then(|cookie| cookie.reply().ok());
358            if version.is_none_or(|v| v.major_version < 2) {
359                return false;
360            }
361        }
362        let mask = if on { xinput::XIEventMask::RAW_MOTION } else { xinput::XIEventMask::from(0u32) };
363        let masks = [xinput::EventMask { deviceid: xinput::Device::ALL_MASTER.into(), mask: vec![mask] }];
364        let selected = self.conn.xinput_xi_select_events(self.root, &masks).is_ok();
365        let _ = self.conn.flush();
366        selected
367    }
368
369    fn warp_to_middle(&self) {
370        if let Some((x, y)) = self.middle() {
371            let _ = self.conn.warp_pointer(x11rb::NONE, self.window, 0, 0, 0, 0, x, y);
372            let _ = self.conn.flush();
373        }
374    }
375
376    /// An invisible cursor: a one-pixel pixmap with nothing set, as its
377    /// image and mask.
378    fn blank_cursor(&self) -> Result<u32, x11rb::errors::ReplyOrIdError> {
379        let pixmap = self.conn.generate_id()?;
380        self.conn.create_pixmap(1, pixmap, self.window, 1, 1)?;
381        let cursor = self.conn.generate_id()?;
382        self.conn.create_cursor(cursor, pixmap, pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
383        self.conn.free_pixmap(pixmap)?;
384        Ok(cursor)
385    }
386}
387
388/// The x and y valuators (0 and 1) of a raw motion, unaccelerated: its
389/// values come in the order of the valuators its mask has, and an axis it
390/// doesn't have didn't move.
391fn raw_motion(event: &xinput::RawMotionEvent) -> Option<(f32, f32)> {
392    let mask = event.valuator_mask.first().copied().unwrap_or(0);
393    let value = |valuator: u32| {
394        if mask & (1 << valuator) == 0 {
395            return 0.0;
396        }
397        let index = (mask & ((1 << valuator) - 1)).count_ones() as usize;
398        event.axisvalues_raw.get(index).map_or(0.0, |v| v.integral as f64 + v.frac as f64 / 4_294_967_296.0)
399    };
400    let (dx, dy) = (value(0), value(1));
401    (dx != 0.0 || dy != 0.0).then_some((dx as f32, dy as f32))
402}
403
404/// A button or a wheel's notch while the pointer is grabbed. X11 has the
405/// wheel as buttons 4 to 7, pressed and released at once.
406fn button_input(event: &ButtonPressEvent, pressed: bool, point: impl Fn(i16, i16) -> Point) -> Option<SurfaceInput> {
407    let modifiers = modifiers(event.state);
408    let scroll = |x: f32, y: f32| SurfaceInput::Scroll { delta: ScrollDelta::Lines { x, y }, modifiers };
409    let button = match event.detail {
410        1 => MouseButton::Primary,
411        2 => MouseButton::Middle,
412        3 => MouseButton::Secondary,
413        4..=7 if !pressed => return None,
414        4 => return Some(scroll(0.0, -1.0)),
415        5 => return Some(scroll(0.0, 1.0)),
416        6 => return Some(scroll(-1.0, 0.0)),
417        7 => return Some(scroll(1.0, 0.0)),
418        8 => MouseButton::Back,
419        9 => MouseButton::Forward,
420        n => MouseButton::Other(n as u16),
421    };
422    Some(SurfaceInput::Button { button, pressed, position: point(event.event_x, event.event_y), modifiers })
423}
424
425/// Modifier keys from an X11 event's state: Mod1 is Alt, Mod4 Super, as
426/// desktops map them.
427pub fn modifiers(state: KeyButMask) -> Modifiers {
428    Modifiers {
429        shift: state.contains(KeyButMask::SHIFT),
430        control: state.contains(KeyButMask::CONTROL),
431        alt: state.contains(KeyButMask::MOD1),
432        meta: state.contains(KeyButMask::MOD4),
433    }
434}
435
436/// A pointer grab on a [`ChildWindow`]; released when dropped.
437pub struct PointerLock {
438    surface: ChildWindow,
439    number: u32,
440}
441
442impl Drop for PointerLock {
443    fn drop(&mut self) {
444        let inner = &self.surface.0;
445        if inner.lock.compare_exchange(self.number, 0, Ordering::AcqRel, Ordering::Acquire).is_err() {
446            return;
447        }
448        inner.watch_grab(false);
449        let _ = inner.conn.ungrab_pointer(x11rb::CURRENT_TIME);
450        inner.select_raw_motion(false);
451        // Wakes the lock's thread, which sees it's no longer locked. An
452        // event sent with no mask goes to the window's own client.
453        let wake = ClientMessageEvent::new(32, inner.window, AtomEnum::INTEGER, [self.number, 0, 0, 0, 0]);
454        let _ = inner.conn.send_event(false, inner.window, EventMask::NO_EVENT, wake);
455        let _ = inner.conn.flush();
456    }
457}
458
459impl Drop for Inner {
460    fn drop(&mut self) {
461        let _ = self.conn.destroy_window(self.window);
462        let _ = self.conn.flush();
463    }
464}
465
466// SAFETY: it owns the window and its connection, destroyed only when it's
467// dropped.
468unsafe impl NativeSurface for ChildWindow {
469    fn window_handle(&self) -> Result<RawWindowHandle, HandleError> {
470        let window = NonZeroU32::new(self.0.window).ok_or(HandleError::Unavailable)?;
471        Ok(RawWindowHandle::Xcb(XcbWindowHandle::new(window)))
472    }
473
474    fn display_handle(&self) -> Result<RawDisplayHandle, HandleError> {
475        let conn = NonNull::new(self.0.conn.get_raw_xcb_connection());
476        Ok(RawDisplayHandle::Xcb(XcbDisplayHandle::new(conn, self.0.screen as i32)))
477    }
478}