use core::cell::Cell;
use core::ffi::{CStr, c_char, c_int, c_long, c_uchar, c_uint, c_ulong};
use core::ptr::{self, NonNull};
use core::str;
use core::sync::atomic::{AtomicBool, Ordering};
use std::env;
use std::ffi::OsStr;
use nadir_core::UVec2;
use nadir_core::log::{debug, warn};
use nadir_sys::linux::libc::{LC_CTYPE, setlocale};
use nadir_sys::linux::x11::{
self as xlib, AllocNone, Atom, CWBackPixel, CWBorderPixel, CWColormap, ClientMessage, Colormap,
Cursor, Display, False, InputOutput, PropModeReplace, Status, True, VisualID, VisualIDMask,
Window, XClientMessageData, XClientMessageEvent, XColor, XEvent, XICRec, XIM, XIMCallback,
XIMPreeditNothing, XIMRec, XIMStatusNothing, XNClientWindow, XNDestroyCallback, XNFilterEvents,
XNFocusWindow, XNInputStyle, XPointer, XSetWindowAttributes, XSizeHints, XVisualInfo, Xlib,
};
use super::super::library::Library;
use crate::PlatformError;
const XLIB: &CStr = c"libX11.so.6";
const XLIB_NAME: &str = "libX11.so.6";
const LOOKUP_START: usize = 64;
const INPUT_METHODS: [(&CStr, &str); 2] = [
(c"", "the one XMODIFIERS names"),
(c"@im=none", "Xlib's own"),
];
static TEXT_INPUT_TAKEN: AtomicBool = AtomicBool::new(false);
struct TextInput {
im: NonNull<XIMRec>,
ic: NonNull<XICRec>,
lost: NonNull<Cell<bool>>,
}
impl TextInput {
fn is_lost(&self) -> bool {
unsafe { self.lost.as_ref() }.get()
}
}
fn new_flag() -> NonNull<Cell<bool>> {
NonNull::from(Box::leak(Box::new(Cell::new(false))))
}
unsafe fn free_flag(flag: NonNull<Cell<bool>>) {
drop(unsafe { Box::from_raw(flag.as_ptr()) });
}
pub(super) struct Connection {
xlib: Xlib,
display: NonNull<Display>,
text: Option<TextInput>,
lookup: Vec<u8>,
}
impl Connection {
pub(super) fn open() -> Result<Self, PlatformError> {
let display_name = env::var_os("DISPLAY");
let wayland = env::var_os("WAYLAND_DISPLAY");
if let Some(error) = missing_display(display_name.as_deref(), wayland.as_deref()) {
return Err(error);
}
let library =
unsafe { Library::open(XLIB) }.map_err(|reason| PlatformError::LibraryNotFound {
library: XLIB_NAME,
reason,
})?;
let xlib =
unsafe { Xlib::load(&library) }.map_err(|missing| PlatformError::MissingSymbols {
library: XLIB_NAME,
symbols: missing.names,
})?;
let display = unsafe { (xlib.XOpenDisplay)(ptr::null()) };
match NonNull::new(display) {
Some(display) => Ok(Self {
xlib,
display,
text: None,
lookup: vec![0; LOOKUP_START],
}),
None => Err(PlatformError::ConnectionFailed {
display: display_name
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default(),
}),
}
}
pub(super) fn display(&self) -> NonNull<Display> {
self.display
}
pub(super) fn visual_format(&self, id: VisualID) -> Option<VisualFormat> {
let info = self.visual_info(id)?;
Some(VisualFormat {
depth: info.depth,
class: info.class,
})
}
fn visual_info(&self, id: VisualID) -> Option<XVisualInfo> {
let mut template = XVisualInfo {
visual: ptr::null_mut(),
visualid: id,
screen: 0,
depth: 0,
class: 0,
red_mask: 0,
green_mask: 0,
blue_mask: 0,
colormap_size: 0,
bits_per_rgb: 0,
};
let mut count = 0;
let infos = unsafe {
(self.xlib.XGetVisualInfo)(
self.display.as_ptr(),
VisualIDMask,
&raw mut template,
&raw mut count,
)
};
if infos.is_null() {
return None;
}
let info = if count > 0 {
Some(unsafe { infos.read() })
} else {
None
};
unsafe { (self.xlib.XFree)(infos.cast()) };
info
}
pub(super) fn root(&self) -> Window {
let screen = unsafe { (self.xlib.XDefaultScreen)(self.display.as_ptr()) };
unsafe { (self.xlib.XRootWindow)(self.display.as_ptr(), screen) }
}
pub(super) fn set_detectable_auto_repeat(&self) -> bool {
let mut supported = False;
let on = unsafe {
(self.xlib.XkbSetDetectableAutoRepeat)(self.display.as_ptr(), True, &raw mut supported)
};
on != False && supported != False
}
pub(super) fn resources(&self) -> Option<String> {
let text = unsafe { (self.xlib.XResourceManagerString)(self.display.as_ptr()) };
if text.is_null() {
return None;
}
let text = unsafe { CStr::from_ptr(text) };
Some(text.to_string_lossy().into_owned())
}
pub(super) fn intern(&self, name: &CStr) -> Atom {
unsafe { (self.xlib.XInternAtom)(self.display.as_ptr(), name.as_ptr(), False) }
}
pub(super) fn create_window(
&self,
root: Window,
size: UVec2,
visual: VisualID,
) -> Option<(Window, Colormap)> {
let info = self.visual_info(visual)?;
let colormap = unsafe {
(self.xlib.XCreateColormap)(self.display.as_ptr(), root, info.visual, AllocNone)
};
let mut attributes = XSetWindowAttributes {
background_pixmap: 0,
background_pixel: 0,
border_pixmap: 0,
border_pixel: 0,
bit_gravity: 0,
win_gravity: 0,
backing_store: 0,
backing_planes: 0,
backing_pixel: 0,
save_under: False,
event_mask: 0,
do_not_propagate_mask: 0,
override_redirect: False,
colormap,
cursor: 0,
};
let mask = CWBackPixel | CWBorderPixel | CWColormap;
let window = unsafe {
(self.xlib.XCreateWindow)(
self.display.as_ptr(),
root,
0,
0,
size.x as c_uint,
size.y as c_uint,
0,
info.depth,
InputOutput,
info.visual,
mask as c_ulong,
&raw mut attributes,
)
};
Some((window, colormap))
}
pub(super) fn free_colormap(&self, colormap: Colormap) {
unsafe { (self.xlib.XFreeColormap)(self.display.as_ptr(), colormap) };
}
pub(super) fn destroy_window(&self, window: Window) {
unsafe { (self.xlib.XDestroyWindow)(self.display.as_ptr(), window) };
}
pub(super) fn map_window(&self, window: Window) {
unsafe { (self.xlib.XMapWindow)(self.display.as_ptr(), window) };
}
pub(super) fn select_input(&self, window: Window, event_mask: c_long) {
unsafe { (self.xlib.XSelectInput)(self.display.as_ptr(), window, event_mask) };
}
pub(super) fn set_protocols(&self, window: Window, protocols: &mut [Atom]) -> bool {
let Ok(count) = c_int::try_from(protocols.len()) else {
return false;
};
let status = unsafe {
(self.xlib.XSetWMProtocols)(
self.display.as_ptr(),
window,
protocols.as_mut_ptr(),
count,
)
};
status != 0
}
pub(super) fn set_bytes(
&self,
window: Window,
property: Atom,
type_: Atom,
data: &[u8],
) -> bool {
let Ok(len) = c_int::try_from(data.len()) else {
return false;
};
unsafe {
(self.xlib.XChangeProperty)(
self.display.as_ptr(),
window,
property,
type_,
8,
PropModeReplace,
data.as_ptr(),
len,
)
};
true
}
pub(super) fn set_atoms(&self, window: Window, property: Atom, type_: Atom, atoms: &[Atom]) {
let Ok(len) = c_int::try_from(atoms.len()) else {
return;
};
unsafe {
(self.xlib.XChangeProperty)(
self.display.as_ptr(),
window,
property,
type_,
32,
PropModeReplace,
atoms.as_ptr().cast::<c_uchar>(),
len,
)
};
}
pub(super) fn set_normal_hints(&self, window: Window, mut hints: XSizeHints) {
unsafe { (self.xlib.XSetWMNormalHints)(self.display.as_ptr(), window, &raw mut hints) };
}
pub(super) fn pending(&self) -> c_int {
unsafe { (self.xlib.XPending)(self.display.as_ptr()) }
}
pub(super) fn next_event(&self) -> XEvent {
let mut event = XEvent { pad: [0; 24] };
unsafe { (self.xlib.XNextEvent)(self.display.as_ptr(), &raw mut event) };
event
}
pub(super) fn send_to_window_manager(
&self,
root: Window,
window: Window,
message_type: Atom,
data: [c_long; 5],
event_mask: c_long,
) -> bool {
let mut event = XEvent { pad: [0; 24] };
event.xclient = XClientMessageEvent {
type_: ClientMessage,
serial: 0,
send_event: True,
display: self.display.as_ptr(),
window,
message_type,
format: 32,
data: XClientMessageData { l: data },
};
let status = unsafe {
(self.xlib.XSendEvent)(
self.display.as_ptr(),
root,
False,
event_mask,
&raw mut event,
)
};
status != 0
}
#[cfg(test)]
pub(super) fn send_key(&self, window: Window, keycode: c_uint, pressed: bool, state: c_uint) {
let mut event = XEvent { pad: [0; 24] };
event.xkey = nadir_sys::linux::x11::XKeyEvent {
type_: if pressed {
xlib::KeyPress
} else {
xlib::KeyRelease
},
serial: 0,
send_event: True,
display: self.display.as_ptr(),
window,
root: self.root(),
subwindow: 0,
time: 0,
x: 0,
y: 0,
x_root: 0,
y_root: 0,
state,
keycode,
same_screen: True,
};
let mask = if pressed {
xlib::KeyPressMask
} else {
xlib::KeyReleaseMask
};
let status = unsafe {
(self.xlib.XSendEvent)(self.display.as_ptr(), window, False, mask, &raw mut event)
};
assert_ne!(status, 0, "XSendEvent could not send a key event");
}
pub(super) fn create_blank_cursor(&self, window: Window) -> Option<Cursor> {
let bits: [c_char; 1] = [0];
let bitmap = unsafe {
(self.xlib.XCreateBitmapFromData)(self.display.as_ptr(), window, bits.as_ptr(), 1, 1)
};
if bitmap == 0 {
return None;
}
let black = XColor {
pixel: 0,
red: 0,
green: 0,
blue: 0,
flags: 0,
pad: 0,
};
let (mut foreground, mut background) = (black, black);
let cursor = unsafe {
(self.xlib.XCreatePixmapCursor)(
self.display.as_ptr(),
bitmap,
bitmap,
&raw mut foreground,
&raw mut background,
0,
0,
)
};
unsafe { (self.xlib.XFreePixmap)(self.display.as_ptr(), bitmap) };
(cursor != 0).then_some(cursor)
}
pub(super) fn define_cursor(&self, window: Window, cursor: Cursor) {
unsafe { (self.xlib.XDefineCursor)(self.display.as_ptr(), window, cursor) };
}
pub(super) fn undefine_cursor(&self, window: Window) {
unsafe { (self.xlib.XUndefineCursor)(self.display.as_ptr(), window) };
}
pub(super) fn free_cursor(&self, cursor: Cursor) {
unsafe { (self.xlib.XFreeCursor)(self.display.as_ptr(), cursor) };
}
}
impl Connection {
pub(super) fn open_text_input(&mut self, window: Window) -> c_long {
self.close_text_input();
if TEXT_INPUT_TAKEN.swap(true, Ordering::Acquire) {
warn!("another window has the X input method: typed text is not reported in this one");
return 0;
}
use_environment_ctype(&self.xlib);
for (modifiers, which) in INPUT_METHODS {
let set = unsafe { (self.xlib.XSetLocaleModifiers)(modifiers.as_ptr()) };
if set.is_null() {
continue;
}
if let Some(text) = self.open_input_method(window) {
let mask = self.filter_events(&text);
debug!("typed text comes from an X input method: {which}");
self.text = Some(text);
return mask;
}
}
TEXT_INPUT_TAKEN.store(false, Ordering::Release);
warn!("no X input method opened: the keys work, and typed text is not reported");
0
}
fn open_input_method(&self, window: Window) -> Option<TextInput> {
let im = unsafe {
(self.xlib.XOpenIM)(
self.display.as_ptr(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)
};
let im = NonNull::new(im)?;
let lost = new_flag();
let close = |im: NonNull<XIMRec>| {
unsafe { (self.xlib.XCloseIM)(im.as_ptr()) };
unsafe { free_flag(lost) };
};
let mut callback = XIMCallback {
client_data: lost.as_ptr().cast::<c_char>(),
callback: Some(input_method_lost),
};
let failed = unsafe {
(self.xlib.XSetIMValues)(
im.as_ptr(),
XNDestroyCallback.as_ptr(),
&raw mut callback,
ptr::null::<c_char>(),
)
};
if !failed.is_null() {
close(im);
return None;
}
let ic = unsafe {
(self.xlib.XCreateIC)(
im.as_ptr(),
XNInputStyle.as_ptr(),
XIMPreeditNothing | XIMStatusNothing,
XNClientWindow.as_ptr(),
window,
XNFocusWindow.as_ptr(),
window,
ptr::null::<c_char>(),
)
};
let Some(ic) = NonNull::new(ic) else {
close(im);
return None;
};
Some(TextInput { im, ic, lost })
}
#[cfg(test)]
pub(super) fn has_text_input(&self) -> bool {
self.text.is_some()
}
fn filter_events(&self, text: &TextInput) -> c_long {
let mut mask: c_ulong = 0;
let failed = unsafe {
(self.xlib.XGetICValues)(
text.ic.as_ptr(),
XNFilterEvents.as_ptr(),
&raw mut mask,
ptr::null::<c_char>(),
)
};
if failed.is_null() {
mask as c_long
} else {
0
}
}
fn live_context(&mut self) -> Option<NonNull<XICRec>> {
if self.text.as_ref()?.is_lost() {
warn!("the X input method stopped: typed text is not reported any more");
self.close_text_input();
return None;
}
self.text.as_ref().map(|text| text.ic)
}
pub(super) unsafe fn filter_event(&self, event: &mut XEvent) -> bool {
unsafe { (self.xlib.XFilterEvent)(event, 0) != False }
}
pub(super) unsafe fn lookup_text(&mut self, event: &mut XEvent) -> &str {
let Some(ic) = self.live_context() else {
return "";
};
for _ in 0..2 {
let room = c_int::try_from(self.lookup.len()).unwrap_or(c_int::MAX);
let mut status: Status = 0;
let length = unsafe {
(self.xlib.Xutf8LookupString)(
ic.as_ptr(),
&raw mut event.xkey,
self.lookup.as_mut_ptr().cast::<c_char>(),
room,
ptr::null_mut(),
&raw mut status,
)
};
let length = usize::try_from(length).unwrap_or(0);
match status {
xlib::XLookupChars | xlib::XLookupBoth => {
let typed = &self.lookup[..length.min(self.lookup.len())];
return str::from_utf8(typed).unwrap_or("");
}
xlib::XBufferOverflow if length > self.lookup.len() => {
self.lookup.resize(length, 0);
}
_ => return "",
}
}
""
}
pub(super) fn set_text_focus(&mut self, focused: bool) {
let Some(ic) = self.live_context() else {
return;
};
if focused {
unsafe { (self.xlib.XSetICFocus)(ic.as_ptr()) };
} else {
unsafe { (self.xlib.XUnsetICFocus)(ic.as_ptr()) };
}
}
pub(super) fn close_text_input(&mut self) {
let Some(text) = self.text.take() else {
return;
};
if !text.is_lost() {
unsafe { (self.xlib.XDestroyIC)(text.ic.as_ptr()) };
unsafe { (self.xlib.XCloseIM)(text.im.as_ptr()) };
}
unsafe { free_flag(text.lost) };
TEXT_INPUT_TAKEN.store(false, Ordering::Release);
}
}
unsafe extern "C" fn input_method_lost(_im: XIM, client_data: XPointer, _call_data: XPointer) {
let lost = unsafe { &*client_data.cast::<Cell<bool>>() };
lost.set(true);
}
fn use_environment_ctype(xlib: &Xlib) {
let current = unsafe { setlocale(LC_CTYPE, ptr::null()) };
if !current.is_null() {
let name = unsafe { CStr::from_ptr(current) };
if name != c"C" && name != c"POSIX" {
return;
}
}
let set = unsafe { setlocale(LC_CTYPE, c"".as_ptr()) };
if set.is_null() {
debug!("the environment names no installed character locale: typed text stays Latin-1");
return;
}
if unsafe { (xlib.XSupportsLocale)() } == False {
unsafe { setlocale(LC_CTYPE, c"C".as_ptr()) };
debug!("Xlib cannot work in the environment's character locale: typed text stays Latin-1");
return;
}
let name = unsafe { setlocale(LC_CTYPE, ptr::null()) };
if !name.is_null() {
let name = unsafe { CStr::from_ptr(name) };
debug!(
"the character locale is the environment's from now on, {:?}, for typed text",
name.to_string_lossy()
);
}
}
impl Drop for Connection {
fn drop(&mut self) {
self.close_text_input();
unsafe { (self.xlib.XCloseDisplay)(self.display.as_ptr()) };
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct VisualFormat {
pub(super) depth: c_int,
pub(super) class: c_int,
}
fn missing_display(display: Option<&OsStr>, wayland: Option<&OsStr>) -> Option<PlatformError> {
let is_set = |value: Option<&OsStr>| value.is_some_and(|value| !value.is_empty());
if is_set(display) {
return None;
}
Some(PlatformError::NoDisplay {
wayland: is_set(wayland),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn check(display: Option<&str>, wayland: Option<&str>) -> Option<PlatformError> {
missing_display(display.map(OsStr::new), wayland.map(OsStr::new))
}
#[test]
fn a_display_is_enough_whatever_else_is_set() {
assert_eq!(check(Some(":0"), None), None);
assert_eq!(check(Some(":1"), Some("wayland-1")), None);
assert_eq!(check(Some("localhost:10.0"), Some("")), None);
}
#[test]
fn no_display_and_no_wayland_is_no_display_server() {
let expected = Some(PlatformError::NoDisplay { wayland: false });
assert_eq!(check(None, None), expected);
assert_eq!(check(Some(""), None), expected);
assert_eq!(check(None, Some("")), expected);
}
#[test]
fn no_display_in_a_wayland_session_says_so() {
let expected = Some(PlatformError::NoDisplay { wayland: true });
assert_eq!(check(None, Some("wayland-0")), expected);
assert_eq!(check(Some(""), Some("wayland-1")), expected);
}
}