pub use crcbl_x11::ffi::*;
use core::ffi::{CStr, c_char, c_int, c_long, c_void};
use std::sync::OnceLock;
use crate::linux::{CLOCK_MONOTONIC, Nfds};
#[repr(C)]
pub struct CursorContext {
_opaque: [u8; 0],
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct XkbUseExtensionReply {
pub response_type: u8,
pub supported: u8,
pub sequence: u16,
pub length: u32,
pub server_major: u16,
pub server_minor: u16,
pub pad0: [u8; 20],
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct ShapeQueryVersionReply {
pub response_type: u8,
pub pad0: u8,
pub sequence: u16,
pub length: u32,
pub major_version: u16,
pub minor_version: u16,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Dri3OpenReply {
pub response_type: u8,
pub nfd: u8,
pub sequence: u16,
pub length: u32,
pub pad0: [u8; 24],
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct XkbPerClientFlagsReply {
pub response_type: u8,
pub device_id: u8,
pub sequence: u16,
pub length: u32,
pub supported: u32,
pub value: u32,
pub auto_ctrls: u32,
pub auto_ctrls_values: u32,
pub pad0: [u8; 8],
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct XiQueryVersionReply {
pub response_type: u8,
pub pad0: u8,
pub sequence: u16,
pub length: u32,
pub major_version: u16,
pub minor_version: u16,
pub pad1: [u8; 20],
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct XiEventMask {
pub deviceid: u16,
pub mask_len: u16,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct XiRawEvent {
pub response_type: u8,
pub extension: u8,
pub sequence: u16,
pub length: u32,
pub event_type: u16,
pub deviceid: u16,
pub time: u32,
pub detail: u32,
pub sourceid: u16,
pub valuators_len: u16,
pub flags: u32,
pub pad0: [u8; 4],
pub full_sequence: u32,
}
pub mod value {
pub use crcbl_x11::ffi::value::*;
pub const XI_ALL_MASTER_DEVICES: u16 = 1;
pub const XI_RAW_MOTION: u16 = 17;
pub const XI_RAW_MOTION_MASK: u32 = 1 << 17;
pub const XKB_USE_CORE_KBD: u16 = 0x0100;
pub const XKB_DETECTABLE_AUTO_REPEAT: u32 = 1;
pub const XKB_MAJOR: u16 = 1;
pub const XKB_MINOR: u16 = 0;
pub const SHAPE_SET: u8 = 0;
pub const SHAPE_INPUT: u8 = 2;
}
unsafe extern "C" {
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
fn poll(fds: *mut PollFd, nfds: Nfds, timeout: c_int) -> c_int;
fn clock_gettime(clock_id: c_int, tp: *mut Timespec) -> c_int;
}
#[repr(C)]
struct PollFd {
fd: c_int,
events: i16,
revents: i16,
}
#[repr(C)]
struct Timespec {
tv_sec: c_long,
tv_nsec: c_long,
}
const POLLIN: i16 = 0x001;
mod prototype {
use super::{
Connection, Cookie, CursorContext, Dri3OpenReply, GenericError, Rectangle, Screen,
ShapeQueryVersionReply, XiEventMask, XiQueryVersionReply, XkbPerClientFlagsReply,
XkbUseExtensionReply, c_char, c_int,
};
pub type XkbUseExtension = unsafe extern "C" fn(*mut Connection, u16, u16) -> Cookie;
pub type XkbUseExtensionReplyFn = unsafe extern "C" fn(
*mut Connection,
Cookie,
*mut *mut GenericError,
) -> *mut XkbUseExtensionReply;
pub type XkbPerClientFlags =
unsafe extern "C" fn(*mut Connection, u16, u32, u32, u32, u32, u32) -> Cookie;
pub type XkbPerClientFlagsReplyFn = unsafe extern "C" fn(
*mut Connection,
Cookie,
*mut *mut GenericError,
) -> *mut XkbPerClientFlagsReply;
pub type XiQueryVersion = unsafe extern "C" fn(*mut Connection, u16, u16) -> Cookie;
pub type XiQueryVersionReplyFn = unsafe extern "C" fn(
*mut Connection,
Cookie,
*mut *mut GenericError,
) -> *mut XiQueryVersionReply;
pub type XiSelectEvents =
unsafe extern "C" fn(*mut Connection, u32, u16, *const XiEventMask) -> Cookie;
pub type CursorContextNew =
unsafe extern "C" fn(*mut Connection, *mut Screen, *mut *mut CursorContext) -> c_int;
pub type CursorLoadCursor = unsafe extern "C" fn(*mut CursorContext, *const c_char) -> u32;
pub type CursorContextFree = unsafe extern "C" fn(*mut CursorContext);
pub type ShapeQueryVersion = unsafe extern "C" fn(*mut Connection) -> Cookie;
pub type ShapeQueryVersionReplyFn = unsafe extern "C" fn(
*mut Connection,
Cookie,
*mut *mut GenericError,
) -> *mut ShapeQueryVersionReply;
pub type ShapeRectangles = unsafe extern "C" fn(
*mut Connection,
u8,
u8,
u8,
u32,
i16,
i16,
u32,
*const Rectangle,
) -> Cookie;
pub type ShapeMask =
unsafe extern "C" fn(*mut Connection, u8, u8, u32, i16, i16, u32) -> Cookie;
pub type Dri3Open = unsafe extern "C" fn(*mut Connection, u32, u32) -> Cookie;
pub type Dri3OpenReplyFn =
unsafe extern "C" fn(*mut Connection, Cookie, *mut *mut GenericError) -> *mut Dri3OpenReply;
pub type Dri3OpenReplyFds =
unsafe extern "C" fn(*mut Connection, *mut Dri3OpenReply) -> *mut c_int;
}
pub struct XiLib {
pub id: usize,
pub query_version: prototype::XiQueryVersion,
pub query_version_reply: prototype::XiQueryVersionReplyFn,
pub select_events: prototype::XiSelectEvents,
}
impl core::fmt::Debug for XiLib {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("XiLib(libxcb-xinput)")
}
}
pub struct XkbLib {
pub use_extension: prototype::XkbUseExtension,
pub use_extension_reply: prototype::XkbUseExtensionReplyFn,
pub per_client_flags: prototype::XkbPerClientFlags,
pub per_client_flags_reply: prototype::XkbPerClientFlagsReplyFn,
}
impl core::fmt::Debug for XkbLib {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("XkbLib(libxcb-xkb)")
}
}
pub struct CursorLib {
pub context_new: prototype::CursorContextNew,
pub load_cursor: prototype::CursorLoadCursor,
pub context_free: prototype::CursorContextFree,
}
impl core::fmt::Debug for CursorLib {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("CursorLib(libxcb-cursor)")
}
}
pub struct ShapeLib {
pub id: usize,
pub query_version: prototype::ShapeQueryVersion,
pub query_version_reply: prototype::ShapeQueryVersionReplyFn,
pub rectangles: prototype::ShapeRectangles,
pub mask: prototype::ShapeMask,
}
impl core::fmt::Debug for ShapeLib {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("ShapeLib(libxcb-shape)")
}
}
pub struct Dri3Lib {
pub id: usize,
pub open: prototype::Dri3Open,
pub open_reply: prototype::Dri3OpenReplyFn,
pub open_reply_fds: prototype::Dri3OpenReplyFds,
}
impl core::fmt::Debug for Dri3Lib {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Dri3Lib(libxcb-dri3)")
}
}
#[derive(Debug)]
pub struct Ext {
pub randr: Option<&'static RandrLib>,
pub xi: Option<&'static XiLib>,
pub xkb: Option<&'static XkbLib>,
pub cursor: Option<&'static CursorLib>,
pub shape: Option<&'static ShapeLib>,
pub dri3: Option<&'static Dri3Lib>,
}
const XI_SONAMES: [&CStr; 2] = [c"libxcb-xinput.so.0", c"libxcb-xinput.so"];
const XKB_SONAMES: [&CStr; 2] = [c"libxcb-xkb.so.1", c"libxcb-xkb.so"];
const CURSOR_SONAMES: [&CStr; 2] = [c"libxcb-cursor.so.0", c"libxcb-cursor.so"];
const SHAPE_SONAMES: [&CStr; 2] = [c"libxcb-shape.so.0", c"libxcb-shape.so"];
const DRI3_SONAMES: [&CStr; 2] = [c"libxcb-dri3.so.0", c"libxcb-dri3.so"];
static RANDR: OnceLock<Option<&'static RandrLib>> = OnceLock::new();
static XI: OnceLock<Option<XiLib>> = OnceLock::new();
static XKB: OnceLock<Option<XkbLib>> = OnceLock::new();
static CURSOR: OnceLock<Option<CursorLib>> = OnceLock::new();
static SHAPE: OnceLock<Option<ShapeLib>> = OnceLock::new();
static DRI3: OnceLock<Option<Dri3Lib>> = OnceLock::new();
#[must_use]
pub fn load_ext() -> Ext {
Ext {
randr: *RANDR.get_or_init(randr_or_warn),
xi: XI.get_or_init(load_xi).as_ref(),
xkb: XKB.get_or_init(load_xkb).as_ref(),
cursor: CURSOR.get_or_init(load_cursor).as_ref(),
shape: SHAPE.get_or_init(load_shape).as_ref(),
dri3: DRI3.get_or_init(load_dri3).as_ref(),
}
}
fn randr_or_warn() -> Option<&'static RandrLib> {
load_randr()
.inspect_err(|detail| {
crcbl_core::log::warn!(
"libxcb-randr is not usable ({detail}): one monitor covering the whole \
screen, and no refresh rate"
);
})
.ok()
}
fn load_xi() -> Option<XiLib> {
let handle = unsafe { open_library(&XI_SONAMES) };
if handle.is_null() {
crcbl_core::log::warn!(
"libxcb-xinput is not available: no unaccelerated pointer motion, so \
ShellCaps::RAW_POINTER_MOTION stays clear"
);
return None;
}
macro_rules! symbol {
($name:literal, $ty:ty) => {{
let raw = unsafe { dlsym(handle, concat!($name, "\0").as_ptr().cast()) };
if raw.is_null() {
crcbl_core::log::warn!("libxcb-xinput has no symbol {}; degrading", $name);
return None;
}
unsafe { core::mem::transmute::<*mut c_void, $ty>(raw) }
}};
}
let id = unsafe { dlsym(handle, c"xcb_input_id".as_ptr()) } as usize;
if id == 0 {
crcbl_core::log::warn!("libxcb-xinput has no xcb_input_id; degrading");
return None;
}
Some(XiLib {
id,
query_version: symbol!("xcb_input_xi_query_version", prototype::XiQueryVersion),
query_version_reply: symbol!(
"xcb_input_xi_query_version_reply",
prototype::XiQueryVersionReplyFn
),
select_events: symbol!("xcb_input_xi_select_events", prototype::XiSelectEvents),
})
}
fn load_xkb() -> Option<XkbLib> {
let handle = unsafe { open_library(&XKB_SONAMES) };
if handle.is_null() {
crcbl_core::log::warn!(
"libxcb-xkb is not available: auto-repeat falls back to the release/press \
lookahead, which misreads a repeat whose two halves arrive in different reads"
);
return None;
}
macro_rules! symbol {
($name:literal, $ty:ty) => {{
let raw = unsafe { dlsym(handle, concat!($name, "\0").as_ptr().cast()) };
if raw.is_null() {
crcbl_core::log::warn!("libxcb-xkb has no symbol {}; degrading", $name);
return None;
}
unsafe { core::mem::transmute::<*mut c_void, $ty>(raw) }
}};
}
Some(XkbLib {
use_extension: symbol!("xcb_xkb_use_extension", prototype::XkbUseExtension),
use_extension_reply: symbol!(
"xcb_xkb_use_extension_reply",
prototype::XkbUseExtensionReplyFn
),
per_client_flags: symbol!("xcb_xkb_per_client_flags", prototype::XkbPerClientFlags),
per_client_flags_reply: symbol!(
"xcb_xkb_per_client_flags_reply",
prototype::XkbPerClientFlagsReplyFn
),
})
}
fn load_cursor() -> Option<CursorLib> {
let handle = unsafe { open_library(&CURSOR_SONAMES) };
if handle.is_null() {
crcbl_core::log::warn!(
"libxcb-cursor is not available: cursor shapes are recorded and not applied, so \
ShellCaps::CURSOR_SHAPE stays clear"
);
return None;
}
macro_rules! symbol {
($name:literal, $ty:ty) => {{
let raw = unsafe { dlsym(handle, concat!($name, "\0").as_ptr().cast()) };
if raw.is_null() {
crcbl_core::log::warn!("libxcb-cursor has no symbol {}; degrading", $name);
return None;
}
unsafe { core::mem::transmute::<*mut c_void, $ty>(raw) }
}};
}
Some(CursorLib {
context_new: symbol!("xcb_cursor_context_new", prototype::CursorContextNew),
load_cursor: symbol!("xcb_cursor_load_cursor", prototype::CursorLoadCursor),
context_free: symbol!("xcb_cursor_context_free", prototype::CursorContextFree),
})
}
fn load_shape() -> Option<ShapeLib> {
let handle = unsafe { open_library(&SHAPE_SONAMES) };
if handle.is_null() {
crcbl_core::log::warn!(
"libxcb-shape is not available: an input region is not applied, so \
ShellCaps::INPUT_REGION stays clear"
);
return None;
}
macro_rules! symbol {
($name:literal, $ty:ty) => {{
let raw = unsafe { dlsym(handle, concat!($name, "\0").as_ptr().cast()) };
if raw.is_null() {
crcbl_core::log::warn!("libxcb-shape has no symbol {}; degrading", $name);
return None;
}
unsafe { core::mem::transmute::<*mut c_void, $ty>(raw) }
}};
}
let id = unsafe { dlsym(handle, c"xcb_shape_id".as_ptr()) } as usize;
if id == 0 {
crcbl_core::log::warn!("libxcb-shape has no xcb_shape_id; degrading");
return None;
}
Some(ShapeLib {
id,
query_version: symbol!("xcb_shape_query_version", prototype::ShapeQueryVersion),
query_version_reply: symbol!(
"xcb_shape_query_version_reply",
prototype::ShapeQueryVersionReplyFn
),
rectangles: symbol!("xcb_shape_rectangles", prototype::ShapeRectangles),
mask: symbol!("xcb_shape_mask", prototype::ShapeMask),
})
}
fn load_dri3() -> Option<Dri3Lib> {
let handle = unsafe { open_library(&DRI3_SONAMES) };
if handle.is_null() {
crcbl_core::log::debug!(
"libxcb-dri3 is not available: the renderer is not told which GPU the X server uses"
);
return None;
}
macro_rules! symbol {
($name:literal, $ty:ty) => {{
let raw = unsafe { dlsym(handle, concat!($name, "\0").as_ptr().cast()) };
if raw.is_null() {
crcbl_core::log::warn!("libxcb-dri3 has no symbol {}; degrading", $name);
return None;
}
unsafe { core::mem::transmute::<*mut c_void, $ty>(raw) }
}};
}
let id = unsafe { dlsym(handle, c"xcb_dri3_id".as_ptr()) } as usize;
if id == 0 {
crcbl_core::log::warn!("libxcb-dri3 has no xcb_dri3_id; degrading");
return None;
}
Some(Dri3Lib {
id,
open: symbol!("xcb_dri3_open", prototype::Dri3Open),
open_reply: symbol!("xcb_dri3_open_reply", prototype::Dri3OpenReplyFn),
open_reply_fds: symbol!("xcb_dri3_open_reply_fds", prototype::Dri3OpenReplyFds),
})
}
#[must_use]
pub fn poll_readable(fd: c_int, timeout_ms: c_int) -> bool {
let mut fds = PollFd {
fd,
events: POLLIN,
revents: 0,
};
let result = unsafe { poll(&raw mut fds, 1, timeout_ms) };
result > 0 && fds.revents & POLLIN != 0
}
#[must_use]
pub fn poll_readable_or(primary: c_int, other: c_int, timeout_ms: c_int) -> bool {
let mut fds = [primary, other].map(|fd| PollFd {
fd,
events: POLLIN,
revents: 0,
});
let count = Nfds::try_from(fds.len()).unwrap_or(1);
let result = unsafe { poll(fds.as_mut_ptr(), count, timeout_ms) };
result > 0 && fds[0].revents & POLLIN != 0
}
#[must_use]
pub fn monotonic_nanos() -> u64 {
let mut ts = Timespec {
tv_sec: 0,
tv_nsec: 0,
};
if unsafe { clock_gettime(CLOCK_MONOTONIC, &raw mut ts) } != 0 {
return 0;
}
let seconds = u64::try_from(ts.tv_sec).unwrap_or(0);
let nanos = u64::try_from(ts.tv_nsec).unwrap_or(0);
seconds * 1_000_000_000 + nanos
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_extension_wire_structures_match_the_c_layout() {
assert_eq!(size_of::<XkbUseExtensionReply>(), 32);
assert_eq!(size_of::<XkbPerClientFlagsReply>(), 32);
assert_eq!(size_of::<ShapeQueryVersionReply>(), 12);
assert_eq!(
size_of::<XiRawEvent>(),
36,
"a GeGeneric's fixed part, with full_sequence inserted at 32"
);
}
#[test]
fn the_monotonic_clock_advances() {
let first = monotonic_nanos();
assert!(first > 0, "CLOCK_MONOTONIC is available on Linux");
assert!(monotonic_nanos() >= first);
}
#[test]
fn polling_a_closed_descriptor_does_not_block() {
assert!(!poll_readable(-1, 0));
}
}