mod connection;
mod input;
use core::ffi::{CStr, c_int, c_long, c_void};
use nadir_core::UVec2;
use nadir_core::log::{debug, error, warn};
use nadir_sys::linux::x11::{
Atom, ButtonPressMask, ButtonReleaseMask, Colormap, Cursor, FocusChangeMask, KeyPressMask,
KeyReleaseMask, PMaxSize, PMinSize, PointerMotionMask, StructureNotifyMask,
SubstructureNotifyMask, SubstructureRedirectMask, TrueColor, Window, XA_ATOM, XA_STRING,
XA_WM_NAME, XAspectRatio, XSizeHints,
};
use self::connection::{Connection, VisualFormat};
use self::input::{CloseMessage, Incoming, Translator};
use super::egl::WindowGl;
use super::xresources;
use crate::{Event, GlContext, GlContextId, GpuSurface, ModalFrame, PlatformError, WindowConfig};
const EVENT_MASK: c_long = KeyPressMask
| KeyReleaseMask
| ButtonPressMask
| ButtonReleaseMask
| PointerMotionMask
| FocusChangeMask
| StructureNotifyMask;
const MAX_DIMENSION: u32 = 32767;
const NET_WM_STATE_REMOVE: c_long = 0;
const NET_WM_STATE_ADD: c_long = 1;
const SOURCE_APPLICATION: c_long = 1;
struct Atoms {
wm_protocols: Atom,
wm_delete_window: Atom,
net_wm_name: Atom,
net_wm_state: Atom,
net_wm_state_fullscreen: Atom,
utf8_string: Atom,
}
impl Atoms {
fn intern(connection: &Connection) -> Self {
Self {
wm_protocols: connection.intern(c"WM_PROTOCOLS"),
wm_delete_window: connection.intern(c"WM_DELETE_WINDOW"),
net_wm_name: connection.intern(c"_NET_WM_NAME"),
net_wm_state: connection.intern(c"_NET_WM_STATE"),
net_wm_state_fullscreen: connection.intern(c"_NET_WM_STATE_FULLSCREEN"),
utf8_string: connection.intern(c"UTF8_STRING"),
}
}
}
pub(crate) struct Backend {
root: Window,
window: Window,
colormap: Colormap,
atoms: Atoms,
translator: Translator,
requested_size: UVec2,
min_size: UVec2,
resizable: bool,
fullscreen: bool,
cursor_visible: bool,
blank_cursor: Option<Cursor>,
gl: WindowGl,
connection: Connection,
}
impl Backend {
pub(crate) fn new(config: &WindowConfig) -> Result<Self, PlatformError> {
let connection = Connection::open()?;
if !connection.set_detectable_auto_repeat() {
warn!(
"the X server has no detectable auto-repeat: a held key will report \
releases and presses in place of repeats"
);
}
let scale = xresources::scale_factor(connection.resources().as_deref());
let requested_size = physical_size(config.size, scale);
let root = connection.root();
let atoms = Atoms::intern(&connection);
let gl = unsafe {
WindowGl::open(connection.display(), |visual| {
connection
.visual_format(visual)
.is_some_and(is_opaque_true_color)
})
}?;
let (window, colormap) = connection
.create_window(root, requested_size, gl.visual())
.ok_or(PlatformError::CallFailed {
call: "XGetVisualInfo",
})?;
let close = CloseMessage {
wm_protocols: atoms.wm_protocols,
wm_delete_window: atoms.wm_delete_window,
};
let mut backend = Self {
root,
window,
colormap,
atoms,
translator: Translator::new(close, requested_size, scale),
requested_size,
min_size: physical_min_size(config.min_size, scale),
resizable: config.resizable,
fullscreen: config.fullscreen,
cursor_visible: true,
blank_cursor: None,
gl,
connection,
};
let typing = backend.connection.open_text_input(window);
backend.connection.select_input(window, EVENT_MASK | typing);
backend.set_title(&config.title);
let mut protocols = [backend.atoms.wm_delete_window];
if !backend.connection.set_protocols(window, &mut protocols) {
return Err(PlatformError::CallFailed {
call: "XSetWMProtocols",
});
}
backend.apply_size_hints();
if config.fullscreen {
backend.connection.set_atoms(
window,
backend.atoms.net_wm_state,
XA_ATOM,
&[backend.atoms.net_wm_state_fullscreen],
);
}
unsafe { backend.gl.make_current(window, config.vsync) }?;
backend.connection.map_window(window);
debug!(
"opened an X11 window of {}x{} pixels at scale {scale}",
requested_size.x, requested_size.y
);
Ok(backend)
}
pub(crate) fn pump_events(&mut self, out: &mut Vec<Event>) {
self.translator.begin_pump(out);
while self.connection.pending() > 0 {
let mut event = self.connection.next_event();
let mut incoming = unsafe { Incoming::decode(&event) };
let taken = unsafe { self.connection.filter_event(&mut event) };
if let Incoming::Key { taken: key, .. } = &mut incoming {
*key = taken;
}
let is_key = matches!(incoming, Incoming::Key { .. });
if taken && !is_key {
continue;
}
self.translator.handle(incoming, out);
if let Incoming::Key {
pressed: true,
state,
..
} = incoming
&& !taken
{
let typed = unsafe { self.connection.lookup_text(&mut event) };
input::push_typed(typed, state, out);
}
if let Some(focused) = input::focus_change(incoming) {
self.connection.set_text_focus(focused);
}
}
}
pub(crate) fn window_size(&self) -> UVec2 {
self.translator.size()
}
pub(crate) fn scale_factor(&self) -> f32 {
self.translator.scale()
}
pub(crate) fn set_fullscreen(&mut self, on: bool) {
if on == self.fullscreen {
return;
}
self.fullscreen = on;
self.apply_size_hints();
let sent = self.connection.send_to_window_manager(
self.root,
self.window,
self.atoms.net_wm_state,
fullscreen_request(on, self.atoms.net_wm_state_fullscreen),
SubstructureNotifyMask | SubstructureRedirectMask,
);
if !sent {
error!("could not ask the window manager for fullscreen: XSendEvent failed");
}
}
pub(crate) fn set_title(&mut self, title: &str) {
let bytes = title.as_bytes();
let modern = self.connection.set_bytes(
self.window,
self.atoms.net_wm_name,
self.atoms.utf8_string,
bytes,
);
let legacy = self.connection.set_bytes(
self.window,
XA_WM_NAME,
legacy_title_type(title, self.atoms.utf8_string),
bytes,
);
if !(modern && legacy) {
error!("the window title is too long to set");
}
}
pub(crate) fn set_cursor_visible(&mut self, visible: bool) {
if visible == self.cursor_visible {
return;
}
if visible {
self.connection.undefine_cursor(self.window);
} else {
if self.blank_cursor.is_none() {
self.blank_cursor = self.connection.create_blank_cursor(self.window);
}
let Some(cursor) = self.blank_cursor else {
error!("could not hide the pointer: the server made no empty cursor");
return;
};
self.connection.define_cursor(self.window, cursor);
}
self.cursor_visible = visible;
}
pub(crate) fn set_modal_frame_callback(&mut self, _callback: Box<dyn FnMut(ModalFrame)>) {
}
pub(crate) fn gpu_surface(&self) -> GpuSurface<'_> {
GpuSurface::Gl(self)
}
fn apply_size_hints(&self) {
let hints = size_hints(
self.requested_size,
self.min_size,
self.resizable,
self.fullscreen,
);
self.connection.set_normal_hints(self.window, hints);
}
}
impl Drop for Backend {
fn drop(&mut self) {
self.gl.release();
self.connection.close_text_input();
if let Some(cursor) = self.blank_cursor.take() {
self.connection.free_cursor(cursor);
}
self.connection.destroy_window(self.window);
self.connection.free_colormap(self.colormap);
}
}
unsafe impl GlContext for Backend {
fn get_proc_address(&self, name: &CStr) -> *const c_void {
self.gl.get_proc_address(name)
}
fn swap_buffers(&self) -> Result<(), PlatformError> {
self.gl.swap_buffers()
}
fn set_swap_interval(&self, interval: i32) -> bool {
self.gl.set_swap_interval(interval)
}
fn drawable_size(&self) -> UVec2 {
self.translator.size()
}
fn context_id(&self) -> Option<GlContextId> {
Some(self.gl.id())
}
}
fn is_opaque_true_color(format: VisualFormat) -> bool {
format.depth == 24 && format.class == TrueColor
}
fn physical_size(logical: UVec2, scale: f32) -> UVec2 {
let dimension = |logical: u32| {
let physical = (logical as f32 * scale).round() as u32;
physical.clamp(1, MAX_DIMENSION)
};
UVec2::new(dimension(logical.x), dimension(logical.y))
}
fn physical_min_size(logical: UVec2, scale: f32) -> UVec2 {
let dimension = |logical: u32| match logical {
0 => 0,
_ => physical_size(UVec2::splat(logical), scale).x,
};
UVec2::new(dimension(logical.x), dimension(logical.y))
}
fn size_hints(size: UVec2, min_size: UVec2, resizable: bool, fullscreen: bool) -> XSizeHints {
let mut hints = XSizeHints {
flags: 0,
x: 0,
y: 0,
width: 0,
height: 0,
min_width: 0,
min_height: 0,
max_width: 0,
max_height: 0,
width_inc: 0,
height_inc: 0,
min_aspect: XAspectRatio { x: 0, y: 0 },
max_aspect: XAspectRatio { x: 0, y: 0 },
base_width: 0,
base_height: 0,
win_gravity: 0,
};
let int = |value: u32| c_int::try_from(value).unwrap_or(c_int::MAX);
if fullscreen {
} else if !resizable {
hints.flags = PMinSize | PMaxSize;
(hints.min_width, hints.min_height) = (int(size.x), int(size.y));
(hints.max_width, hints.max_height) = (int(size.x), int(size.y));
} else if min_size != UVec2::ZERO {
hints.flags = PMinSize;
(hints.min_width, hints.min_height) = (int(min_size.x.max(1)), int(min_size.y.max(1)));
}
hints
}
fn fullscreen_request(on: bool, net_wm_state_fullscreen: Atom) -> [c_long; 5] {
let action = if on {
NET_WM_STATE_ADD
} else {
NET_WM_STATE_REMOVE
};
let state = net_wm_state_fullscreen as c_long;
[action, state, 0, SOURCE_APPLICATION, 0]
}
fn legacy_title_type(title: &str, utf8_string: Atom) -> Atom {
if title.is_ascii() {
XA_STRING
} else {
utf8_string
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_logical_size_is_scaled_and_rounded() {
let size = UVec2::new(640, 360);
assert_eq!(physical_size(size, 1.0), UVec2::new(640, 360));
assert_eq!(physical_size(size, 2.0), UVec2::new(1280, 720));
assert_eq!(physical_size(size, 1.5), UVec2::new(960, 540));
assert_eq!(physical_size(size, 0.75), UVec2::new(480, 270));
assert_eq!(physical_size(UVec2::new(101, 3), 1.25), UVec2::new(126, 4));
assert_eq!(physical_size(UVec2::new(3, 1), 1.5), UVec2::new(5, 2));
}
#[test]
fn a_physical_size_is_one_that_x_can_make() {
assert_eq!(physical_size(UVec2::ZERO, 1.0), UVec2::new(1, 1));
assert_eq!(physical_size(UVec2::new(1, 1), 0.25), UVec2::new(1, 1));
assert_eq!(
physical_size(UVec2::new(u32::MAX, 40_000), 1.0),
UVec2::new(32767, 32767)
);
assert_eq!(
physical_size(UVec2::new(20_000, 100), 2.0),
UVec2::new(32767, 200)
);
assert_eq!(
physical_size(UVec2::new(640, 360), f32::NAN),
UVec2::new(1, 1)
);
assert_eq!(
physical_size(UVec2::new(640, 360), f32::INFINITY),
UVec2::new(32767, 32767)
);
}
#[test]
fn a_minimum_size_is_scaled_and_zero_stays_no_limit() {
assert_eq!(
physical_min_size(UVec2::new(320, 180), 2.0),
UVec2::new(640, 360)
);
assert_eq!(physical_min_size(UVec2::ZERO, 2.0), UVec2::ZERO);
assert_eq!(
physical_min_size(UVec2::new(0, 180), 1.5),
UVec2::new(0, 270)
);
assert_eq!(physical_min_size(UVec2::new(1, 0), 0.25), UVec2::new(1, 0));
}
fn limits(hints: &XSizeHints) -> (c_long, [c_int; 4]) {
(
hints.flags,
[
hints.min_width,
hints.min_height,
hints.max_width,
hints.max_height,
],
)
}
#[test]
fn a_window_of_fixed_size_has_equal_limits() {
let hints = size_hints(UVec2::new(640, 360), UVec2::new(320, 180), false, false);
assert_eq!(limits(&hints), (PMinSize | PMaxSize, [640, 360, 640, 360]));
}
#[test]
fn a_resizable_window_has_only_its_minimum() {
let size = UVec2::new(640, 360);
let hints = size_hints(size, UVec2::new(320, 180), true, false);
assert_eq!(limits(&hints), (PMinSize, [320, 180, 0, 0]));
let hints = size_hints(size, UVec2::ZERO, true, false);
assert_eq!(limits(&hints), (0, [0, 0, 0, 0]));
let hints = size_hints(size, UVec2::new(0, 180), true, false);
assert_eq!(limits(&hints), (PMinSize, [1, 180, 0, 0]));
}
#[test]
fn a_fullscreen_window_has_no_limits() {
for resizable in [false, true] {
let hints = size_hints(UVec2::new(640, 360), UVec2::new(320, 180), resizable, true);
assert_eq!(limits(&hints), (0, [0, 0, 0, 0]));
}
}
#[test]
fn hints_set_nothing_but_the_limits() {
let hints = size_hints(UVec2::new(640, 360), UVec2::new(320, 180), false, false);
let rest = [
hints.x,
hints.y,
hints.width,
hints.height,
hints.width_inc,
hints.height_inc,
hints.min_aspect.x,
hints.min_aspect.y,
hints.max_aspect.x,
hints.max_aspect.y,
hints.base_width,
hints.base_height,
hints.win_gravity,
];
assert_eq!(rest, [0; 13]);
}
#[test]
fn a_fullscreen_request_adds_or_removes_the_state() {
const FULLSCREEN: Atom = 411;
assert_eq!(fullscreen_request(true, FULLSCREEN), [1, 411, 0, 1, 0]);
assert_eq!(fullscreen_request(false, FULLSCREEN), [0, 411, 0, 1, 0]);
}
#[test]
fn only_an_ascii_title_is_a_latin_1_string() {
const UTF8_STRING: Atom = 400;
assert_eq!(legacy_title_type("Nadir", UTF8_STRING), XA_STRING);
assert_eq!(legacy_title_type("", UTF8_STRING), XA_STRING);
assert_eq!(legacy_title_type("Nadir: level 2!", UTF8_STRING), XA_STRING);
assert_eq!(legacy_title_type("Café", UTF8_STRING), UTF8_STRING);
assert_eq!(legacy_title_type("ナディア", UTF8_STRING), UTF8_STRING);
}
#[test]
fn only_an_opaque_true_color_visual_is_taken() {
let (true_color, direct_color) = (4, 5);
let format = |depth, class| VisualFormat { depth, class };
assert!(is_opaque_true_color(format(24, true_color)));
assert!(!is_opaque_true_color(format(32, true_color)));
assert!(!is_opaque_true_color(format(30, true_color)));
assert!(!is_opaque_true_color(format(24, direct_color)));
}
#[test]
#[ignore = "opens windows: run it with --ignored --test-threads=1 in an X11 or XWayland session"]
fn a_window_gets_an_opengl_3_3_core_context_each_time() {
for _ in 0..3 {
let config = WindowConfig {
title: "Nadir test".to_string(),
size: UVec2::new(320, 180),
min_size: UVec2::ZERO,
resizable: true,
fullscreen: false,
vsync: true,
};
let backend = Backend::new(&config).unwrap();
let GpuSurface::Gl(gl) = backend.gpu_surface();
super::super::egl::gl_test::check_context_and_draw(gl);
assert!(gl.context_id().is_some_and(GlContextId::is_current));
assert_eq!(gl.drawable_size(), backend.window_size());
assert!(!gl.set_swap_interval(-1));
for _ in 0..3 {
gl.swap_buffers().unwrap();
}
}
}
#[test]
#[ignore = "opens a window: run it with --ignored --test-threads=1 in an X11 or XWayland session"]
fn key_presses_sent_to_the_window_type_text_through_its_input_method() {
use core::ffi::c_uint;
const A: c_uint = 30 + 8;
const LEFT_SHIFT: c_uint = 42 + 8;
const LEFT_CONTROL: c_uint = 29 + 8;
const ENTER: c_uint = 28 + 8;
const LEFT_ALT: c_uint = 56 + 8;
const SHIFT_MASK: c_uint = 1 << 0;
const CONTROL_MASK: c_uint = nadir_sys::linux::x11::ControlMask;
const MOD1_MASK: c_uint = nadir_sys::linux::x11::Mod1Mask;
let config = WindowConfig {
title: "Nadir test".to_string(),
size: UVec2::new(320, 180),
min_size: UVec2::ZERO,
resizable: true,
fullscreen: false,
vsync: true,
};
let mut backend = Backend::new(&config).unwrap();
assert!(
backend.connection.has_text_input(),
"no X input method opened"
);
backend.connection.set_text_focus(true);
let sent = [
(A, true, 0),
(A, false, 0),
(LEFT_SHIFT, true, 0),
(A, true, SHIFT_MASK),
(A, false, SHIFT_MASK),
(LEFT_SHIFT, false, SHIFT_MASK),
(LEFT_CONTROL, true, 0),
(A, true, CONTROL_MASK),
(A, false, CONTROL_MASK),
(LEFT_CONTROL, false, CONTROL_MASK),
(LEFT_ALT, true, 0),
(A, true, MOD1_MASK),
(A, false, MOD1_MASK),
(LEFT_ALT, false, MOD1_MASK),
(ENTER, true, 0),
(ENTER, false, 0),
];
for (keycode, pressed, state) in sent {
backend
.connection
.send_key(backend.window, keycode, pressed, state);
}
let mut out = Vec::new();
let typed = |out: &[Event]| -> Vec<(usize, char)> {
out.iter()
.enumerate()
.filter_map(|(at, event)| match *event {
Event::Text(typed) => Some((at, typed)),
_ => None,
})
.collect()
};
let start = std::time::Instant::now();
let mut settled = None;
while start.elapsed() < std::time::Duration::from_secs(5) {
backend.pump_events(&mut out);
if typed(&out).len() >= 2 {
let since = *settled.get_or_insert_with(std::time::Instant::now);
if since.elapsed() > std::time::Duration::from_millis(200) {
break;
}
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
let typed = typed(&out);
let characters: Vec<char> = typed.iter().map(|&(_, typed)| typed).collect();
assert_eq!(characters, ['a', 'A'], "{out:?}");
let presses: Vec<usize> = out
.iter()
.enumerate()
.filter(|(_, event)| {
**event
== Event::Key {
key: nadir_core::Key::A,
pressed: true,
repeat: false,
}
})
.map(|(at, _)| at)
.collect();
assert_eq!(presses.len(), 4, "{out:?}");
assert!(
presses[0] < typed[0].0 && typed[0].0 < presses[1],
"{out:?}"
);
assert!(presses[1] < typed[1].0, "{out:?}");
}
#[test]
fn the_event_mask_selects_what_the_translator_handles() {
let expected = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 6) | (1 << 17) | (1 << 21);
assert_eq!(EVENT_MASK, expected);
}
}