wingy-x11 0.31.1

Wingy's X11 backend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use std::collections::HashMap;
use std::error::Error;
use std::ffi::c_int;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard};
use std::{fmt, ptr};

use rwh_06::HasDisplayHandle;
use wingy_core::cursor::CursorIcon;
use x11rb::connection::{Connection, RequestConnection};
use x11rb::errors::ReplyError;
use x11rb::protocol::randr::ConnectionExt as _;
use x11rb::protocol::xproto::{self, ConnectionExt};
use x11rb::protocol::{ErrorKind, randr, render};
use x11rb::xcb_ffi::XCBConnection;
use x11rb::{CURRENT_TIME, resource_manager};

use super::atoms::Atoms;
use super::ffi;
use super::monitor::MonitorHandle;
use crate::event_loop::{CookieResultExt as _, X11Error};

/// A connection to an X server.
pub struct XConnection {
    pub xlib: ffi::Xlib,

    // TODO(notgull): I'd like to remove this, but apparently Xlib and Xinput2 are tied together
    // for some reason.
    pub xinput2: ffi::XInput2,

    _xfixes: x11_dl::xfixes::Xlib,

    pub display: *mut ffi::Display,

    /// The manager for the XCB connection.
    ///
    /// The `Option` ensures that we can drop it before we close the `Display`.
    xcb: Option<XCBConnection>,

    /// The atoms used by `wingy`.
    ///
    /// This is a large structure, so I've elected to Box it to make accessing the fields of
    /// this struct easier. Feel free to unbox it if you like kicking puppies.
    atoms: Box<Atoms>,

    /// The index of the default screen.
    default_screen: usize,

    /// The last timestamp received by this connection.
    timestamp: AtomicU32,

    /// List of monitor handles.
    pub monitor_handles: Mutex<Option<Vec<MonitorHandle>>>,

    /// The resource database.
    database: RwLock<resource_manager::Database>,

    /// RandR version.
    randr_version: (u32, u32),

    /// Atom for the XSettings screen.
    xsettings_screen: Option<xproto::Atom>,

    /// XRender format information.
    render_formats: render::QueryPictFormatsReply,

    pub latest_error: Mutex<Option<XError>>,
    pub cursor_cache: Mutex<HashMap<Option<CursorIcon>, xproto::Cursor>>,
}

impl HasDisplayHandle for XConnection {
    fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
        let raw = self.raw_display_handle()?;
        unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
    }
}

unsafe impl Send for XConnection {}
unsafe impl Sync for XConnection {}

pub type XErrorHandler =
    Option<unsafe extern "C" fn(*mut ffi::Display, *mut ffi::XErrorEvent) -> std::os::raw::c_int>;

impl XConnection {
    pub fn new(error_handler: XErrorHandler) -> Result<XConnection, XNotSupported> {
        // opening the libraries
        let xlib = ffi::Xlib::open()?;
        let xlib_xcb = ffi::Xlib_xcb::open()?;
        let xinput2 = ffi::XInput2::open()?;
        let xfixes = x11_dl::xfixes::Xlib::open()?;

        unsafe { (xlib.XInitThreads)() };
        unsafe { (xlib.XSetErrorHandler)(error_handler) };

        // calling XOpenDisplay
        let display = unsafe {
            let display = (xlib.XOpenDisplay)(ptr::null());
            if display.is_null() {
                return Err(XNotSupported::XOpenDisplayFailed);
            }
            display
        };

        // Register XFixes event converters
        let (mut event_base, mut error_base) = (0, 0);
        unsafe { (xfixes.XFixesQueryExtension)(display, &mut event_base, &mut error_base) };

        // Open the x11rb XCB connection.
        let xcb = {
            // Get a pointer to the underlying XCB connection
            let xcb_connection =
                unsafe { (xlib_xcb.XGetXCBConnection)(display as *mut ffi::Display) };
            assert!(!xcb_connection.is_null());

            // Wrap the XCB connection in an x11rb XCB connection
            let conn =
                unsafe { XCBConnection::from_raw_xcb_connection(xcb_connection.cast(), false) };

            conn.map_err(|e| XNotSupported::XcbConversionError(Arc::new(WrapConnectError(e))))?
        };

        // Get the default screen.
        let default_screen = unsafe { (xlib.XDefaultScreen)(display) } as usize;

        // Load the database.
        let database = resource_manager::new_from_default(&xcb)
            .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;

        // Load the RandR version.
        xcb.extension_information(randr::X11_EXTENSION_NAME)
            .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?
            .ok_or(XNotSupported::ExtensionNotSupported(
                "the X11 backend requires XRandR 1.2 or newer",
            ))?;
        let randr_version = xcb
            .randr_query_version(1, 3)
            .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?
            .reply()
            .map_err(|e| match e {
                ReplyError::X11Error(error) if error.error_kind == ErrorKind::Request => {
                    XNotSupported::ExtensionNotSupported(
                        "the X11 backend requires XRandR 1.2 or newer",
                    )
                },
                error => XNotSupported::XcbConversionError(Arc::new(error)),
            })?;
        if (randr_version.major_version, randr_version.minor_version) < (1, 2) {
            return Err(XNotSupported::ExtensionNotSupported(
                "the X11 backend requires XRandR 1.2 or newer",
            ));
        }

        let xsettings_screen = Self::new_xsettings_screen(&xcb, default_screen);
        if xsettings_screen.is_none() {
            tracing::warn!("error setting XSETTINGS; Xft options won't reload automatically")
        }

        // Start getting the XRender formats.
        let formats_cookie = render::query_pict_formats(&xcb)
            .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;

        // Fetch atoms.
        let atoms = Atoms::new(&xcb)
            .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?
            .reply()
            .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;

        // Finish getting everything else.
        let formats =
            formats_cookie.reply().map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?;

        Ok(XConnection {
            xlib,
            xinput2,
            _xfixes: xfixes,
            display,
            xcb: Some(xcb),
            atoms: Box::new(atoms),
            default_screen,
            timestamp: AtomicU32::new(0),
            latest_error: Mutex::new(None),
            monitor_handles: Mutex::new(None),
            database: RwLock::new(database),
            cursor_cache: Default::default(),
            randr_version: (randr_version.major_version, randr_version.minor_version),
            render_formats: formats,
            xsettings_screen,
        })
    }

    fn new_xsettings_screen(xcb: &XCBConnection, default_screen: usize) -> Option<xproto::Atom> {
        // Fetch the _XSETTINGS_S[screen number] atom.
        let xsettings_screen = xcb
            .intern_atom(false, format!("_XSETTINGS_S{default_screen}").as_bytes())
            .ok()?
            .reply()
            .ok()?
            .atom;

        // Get PropertyNotify events from the XSETTINGS window.
        // TODO: The XSETTINGS window here can change. In the future, listen for DestroyNotify on
        // this window in order to accommodate for a changed window here.
        let selector_window = xcb.get_selection_owner(xsettings_screen).ok()?.reply().ok()?.owner;

        xcb.change_window_attributes(
            selector_window,
            &xproto::ChangeWindowAttributesAux::new()
                .event_mask(xproto::EventMask::PROPERTY_CHANGE),
        )
        .ok()?
        .check()
        .ok()?;

        Some(xsettings_screen)
    }

    /// Checks whether an error has been triggered by the previous function calls.
    #[inline]
    pub fn check_errors(&self) -> Result<(), XError> {
        let error = self.latest_error.lock().unwrap().take();
        if let Some(error) = error { Err(error) } else { Ok(()) }
    }

    #[inline]
    pub fn randr_version(&self) -> (u32, u32) {
        self.randr_version
    }

    /// Get the underlying XCB connection.
    #[inline]
    pub fn xcb_connection(&self) -> &XCBConnection {
        self.xcb.as_ref().expect("xcb_connection somehow called after drop?")
    }

    /// Get the list of atoms.
    #[inline]
    pub fn atoms(&self) -> &Atoms {
        &self.atoms
    }

    /// Get the index of the default screen.
    #[inline]
    pub fn default_screen_index(&self) -> usize {
        self.default_screen
    }

    /// Get the default screen.
    #[inline]
    pub fn default_root(&self) -> &xproto::Screen {
        &self.xcb_connection().setup().roots[self.default_screen]
    }

    /// Get the resource database.
    #[inline]
    pub fn database(&self) -> RwLockReadGuard<'_, resource_manager::Database> {
        self.database.read().unwrap_or_else(|e| e.into_inner())
    }

    /// Reload the resource database.
    #[inline]
    pub fn reload_database(&self) -> Result<(), X11Error> {
        let database = resource_manager::new_from_default(self.xcb_connection())?;
        *self.database.write().unwrap_or_else(|e| e.into_inner()) = database;
        Ok(())
    }

    /// Get the latest timestamp.
    #[inline]
    pub fn timestamp(&self) -> u32 {
        self.timestamp.load(Ordering::Relaxed)
    }

    /// Set the last witnessed timestamp.
    #[inline]
    pub fn set_timestamp(&self, timestamp: u32) {
        // Store the timestamp in the slot if it's greater than the last one.
        let mut last_timestamp = self.timestamp.load(Ordering::Relaxed);
        loop {
            if (timestamp as i32).wrapping_sub(last_timestamp as i32) <= 0 {
                break;
            }

            match self.timestamp.compare_exchange(
                last_timestamp,
                timestamp,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => break,
                Err(x) => last_timestamp = x,
            }
        }
    }

    /// Get the atom for Xsettings.
    #[inline]
    pub fn xsettings_screen(&self) -> Option<xproto::Atom> {
        self.xsettings_screen
    }

    /// Get the data containing our rendering formats.
    #[inline]
    pub fn render_formats(&self) -> &render::QueryPictFormatsReply {
        &self.render_formats
    }

    /// Do we need to do an endian swap?
    #[inline]
    pub fn needs_endian_swap(&self) -> bool {
        #[cfg(target_endian = "big")]
        let endian = xproto::ImageOrder::MSB_FIRST;
        #[cfg(not(target_endian = "big"))]
        let endian = xproto::ImageOrder::LSB_FIRST;

        self.xcb_connection().setup().image_byte_order != endian
    }

    pub fn raw_display_handle(&self) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
        let display_handle = rwh_06::XlibDisplayHandle::new(
            // SAFETY: display will never be null
            Some(
                std::ptr::NonNull::new(self.display as *mut _)
                    .expect("X11 display should never be null"),
            ),
            self.default_screen_index() as c_int,
        );

        Ok(display_handle.into())
    }

    /// Issues a request to convert a selection (e.g. atoms[XdndSelection], atoms[Clipboard]) to a
    /// particular target type. The result is sent in a [`xproto::SelectionNotifyEvent`].
    pub fn convert_selection(
        &self,
        xwindow: xproto::Window,
        selection: xproto::Atom,
        target: xproto::Atom,
        property: xproto::Atom,
    ) -> Result<(), X11Error> {
        trace!(
            "Requesting {} from selection {} into property {}",
            self.atom_str(target),
            self.atom_str(selection),
            self.atom_str(property),
        );

        let owner = self.xcb_connection().get_selection_owner(selection)?.reply()?.owner;
        if owner == 0 {
            return Err(X11Error::UnexpectedNull("selection owner"));
        }

        self.xcb_connection()
            .convert_selection(xwindow, selection, target, property, CURRENT_TIME)?
            .check()?;

        Ok(())
    }

    /// Get the window owning the selection, or `None`.
    pub fn selection_owner(
        &self,
        selection: xproto::Atom,
    ) -> Result<Option<xproto::Window>, X11Error> {
        let owner = self.xcb_connection().get_selection_owner(selection)?.reply()?.owner;

        Ok((owner != 0).then_some(owner))
    }

    /// Sets the owner of the [`SelectionType`] so applications requesting it will send an
    /// [`xproto::SelectionRequestEvent`] event to us.
    pub fn set_selection_owner(&self, xwindow: xproto::Window, selection: xproto::Atom) {
        self.xcb_connection()
            .set_selection_owner(
                xwindow,
                selection,
                // TODO: Using the current time is not the suggested convention but it doesn't seem
                // to matter https://xorg.freedesktop.org/archive/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#acquiring_selection_ownership
                CURRENT_TIME,
            )
            .expect_then_ignore_error("Failed to send SetSelectionOwner event")
    }

    /// Gets a user readable string of the atom:
    /// - If possible, get the name from the X server
    /// - Otherwise, pretty print as Atom(123)
    #[must_use]
    pub fn atom_str(&self, atom: xproto::Atom) -> String {
        let atom_name = self.xcb_connection().get_atom_name(atom).ok();
        atom_name
            .and_then(|cookie| cookie.reply().ok())
            .and_then(|reply| String::from_utf8(reply.name).ok())
            .unwrap_or_else(|| format!("Atom({atom})"))
    }
}

impl fmt::Debug for XConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.display.fmt(f)
    }
}

impl Drop for XConnection {
    #[inline]
    fn drop(&mut self) {
        self.xcb = None;
        unsafe { (self.xlib.XCloseDisplay)(self.display) };
    }
}

/// Error triggered by xlib.
#[derive(Debug, Clone)]
pub struct XError {
    pub description: String,
    pub error_code: u8,
    pub request_code: u8,
    pub minor_code: u8,
}

impl Error for XError {}

impl fmt::Display for XError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(
            formatter,
            "X error: {} (code: {}, request code: {}, minor code: {})",
            self.description, self.error_code, self.request_code, self.minor_code
        )
    }
}

/// Error returned if this system doesn't support the X11 backend.
#[derive(Clone, Debug)]
pub enum XNotSupported {
    /// Failed to load one or several shared libraries.
    LibraryOpenError(ffi::OpenError),

    /// Connecting to the X server with `XOpenDisplay` failed.
    XOpenDisplayFailed, // TODO: add better message.

    /// We encountered an error while converting the connection to XCB.
    XcbConversionError(Arc<dyn Error + Send + Sync + 'static>),

    /// A required X11 extension is not supported.
    ExtensionNotSupported(&'static str),
}

impl From<ffi::OpenError> for XNotSupported {
    #[inline]
    fn from(err: ffi::OpenError) -> XNotSupported {
        XNotSupported::LibraryOpenError(err)
    }
}

impl XNotSupported {
    fn description(&self) -> &'static str {
        match self {
            XNotSupported::LibraryOpenError(_) => "Failed to load one of xlib's shared libraries",
            XNotSupported::XOpenDisplayFailed => "Failed to open connection to X server",
            XNotSupported::XcbConversionError(_) => "Failed to convert Xlib connection to XCB",
            XNotSupported::ExtensionNotSupported(reason) => reason,
        }
    }
}

impl Error for XNotSupported {
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            XNotSupported::LibraryOpenError(ref err) => Some(err),
            XNotSupported::XcbConversionError(ref err) => Some(&**err),
            _ => None,
        }
    }
}

impl fmt::Display for XNotSupported {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        formatter.write_str(self.description())
    }
}

/// A newtype wrapper around a `ConnectError` that can't be accessed by downstream libraries.
///
/// Without this, `x11rb` would become a public dependency.
#[derive(Debug)]
struct WrapConnectError(x11rb::rust_connection::ConnectError);

impl fmt::Display for WrapConnectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl Error for WrapConnectError {
    // We can't implement `source()` here or otherwise risk exposing `x11rb`.
}