use super::*;
unsafe extern "C" {
fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
pub(crate) fn linux_dlsym(handle: *mut c_void, sym: &'static str) -> *mut c_void {
if handle.is_null() {
return null_mut();
}
unsafe { dlsym(handle, sym.as_ptr().cast::<c_char>()) }
}
pub(crate) fn linux_x11_syms() -> &'static LinuxX11Syms {
LINUX_X11_SYMS.get_or_init(|| -> LinuxX11Syms {
unsafe {
let x11: *mut c_void = dlopen(LINUX_LIB_X11.as_ptr().cast::<c_char>(), RTLD_LAZY);
if x11.is_null() {
return LinuxX11Syms::default();
}
LinuxX11Syms {
lib: x11 as usize,
open_display: linux_dlsym(x11, SYM_X_OPEN_DISPLAY) as usize,
default_screen: linux_dlsym(x11, SYM_X_DEFAULT_SCREEN) as usize,
root_window: linux_dlsym(x11, SYM_X_ROOT_WINDOW) as usize,
create_simple_window: linux_dlsym(x11, SYM_X_CREATE_SIMPLE_WINDOW) as usize,
store_name: linux_dlsym(x11, SYM_X_STORE_NAME) as usize,
map_window: linux_dlsym(x11, SYM_X_MAP_WINDOW) as usize,
resize_window: linux_dlsym(x11, SYM_X_RESIZE_WINDOW) as usize,
destroy_window: linux_dlsym(x11, SYM_X_DESTROY_WINDOW) as usize,
flush: linux_dlsym(x11, SYM_X_FLUSH) as usize,
default_gc: linux_dlsym(x11, SYM_X_DEFAULT_GC) as usize,
default_visual: linux_dlsym(x11, SYM_X_DEFAULT_VISUAL) as usize,
default_depth: linux_dlsym(x11, SYM_X_DEFAULT_DEPTH) as usize,
create_image: linux_dlsym(x11, SYM_X_CREATE_IMAGE) as usize,
put_image: linux_dlsym(x11, SYM_X_PUT_IMAGE) as usize,
free: linux_dlsym(x11, SYM_X_FREE) as usize,
select_input: linux_dlsym(x11, SYM_X_SELECT_INPUT) as usize,
intern_atom: linux_dlsym(x11, SYM_X_INTERN_ATOM) as usize,
set_wm_protocols: linux_dlsym(x11, SYM_X_SET_WM_PROTOCOLS) as usize,
pending: linux_dlsym(x11, SYM_X_PENDING) as usize,
next_event: linux_dlsym(x11, SYM_X_NEXT_EVENT) as usize,
lookup_string: linux_dlsym(x11, SYM_X_LOOKUP_STRING) as usize,
resource_manager_string: linux_dlsym(x11, SYM_X_RESOURCE_MANAGER_STRING) as usize,
}
}
})
}
pub(crate) fn linux_xrandr_syms() -> &'static LinuxXRandrSyms {
LINUX_XRANDR_SYMS.get_or_init(|| -> LinuxXRandrSyms {
unsafe {
let xrandr: *mut c_void = dlopen(LINUX_LIB_XRANDR.as_ptr().cast::<c_char>(), RTLD_LAZY);
if xrandr.is_null() {
return LinuxXRandrSyms::default();
}
LinuxXRandrSyms {
get_screen_info: linux_dlsym(xrandr, SYM_XRR_GET_SCREEN_INFO) as usize,
config_current_rate: linux_dlsym(xrandr, SYM_XRR_CONFIG_CURRENT_RATE) as usize,
free_screen_config_info: linux_dlsym(xrandr, SYM_XRR_FREE_SCREEN_CONFIG_INFO)
as usize,
}
}
})
}
pub(crate) fn linux_xshm_syms() -> &'static LinuxXShmSyms {
LINUX_XSHM_SYMS.get_or_init(|| -> LinuxXShmSyms {
unsafe {
let xext: *mut c_void = dlopen(LINUX_LIB_XEXT.as_ptr().cast::<c_char>(), RTLD_LAZY);
if xext.is_null() {
return LinuxXShmSyms::default();
}
LinuxXShmSyms {
query_extension: linux_dlsym(xext, SYM_XSHM_QUERY_EXTENSION) as usize,
create_image: linux_dlsym(xext, SYM_XSHM_CREATE_IMAGE) as usize,
attach: linux_dlsym(xext, SYM_XSHM_ATTACH) as usize,
detach: linux_dlsym(xext, SYM_XSHM_DETACH) as usize,
put_image: linux_dlsym(xext, SYM_XSHM_PUT_IMAGE) as usize,
}
}
})
}
pub(crate) fn linux_wayland_syms() -> &'static LinuxWaylandSyms {
LINUX_WAYLAND_SYMS.get_or_init(|| -> LinuxWaylandSyms {
unsafe {
let wl: *mut c_void = dlopen(LINUX_LIB_WAYLAND.as_ptr().cast::<c_char>(), RTLD_LAZY);
if wl.is_null() {
return LinuxWaylandSyms::default();
}
let vk: *mut c_void = dlopen(LINUX_LIB_VULKAN.as_ptr().cast::<c_char>(), RTLD_LAZY);
let vulkan_wsi_available: bool =
!vk.is_null() && !linux_dlsym(vk, SYM_VK_CREATE_WAYLAND_SURFACE).is_null();
LinuxWaylandSyms {
lib: wl as usize,
display_connect: linux_dlsym(wl, SYM_WL_DISPLAY_CONNECT) as usize,
display_disconnect: linux_dlsym(wl, SYM_WL_DISPLAY_DISCONNECT) as usize,
display_dispatch_pending: linux_dlsym(wl, SYM_WL_DISPLAY_DISPATCH_PENDING) as usize,
display_dispatch: linux_dlsym(wl, SYM_WL_DISPLAY_DISPATCH) as usize,
display_flush: linux_dlsym(wl, SYM_WL_DISPLAY_FLUSH) as usize,
display_roundtrip: linux_dlsym(wl, SYM_WL_DISPLAY_ROUNDTRIP) as usize,
vulkan_wsi_available,
}
}
})
}
#[must_use]
pub(crate) fn linux_display_refresh_rate_hz(display: *mut c_void, window: usize) -> f32 {
if let Ok(val) = env::var(LINUX_REFRESH_ENV_VAR)
&& let Ok(parsed) = val.trim().parse::<f32>()
&& parsed.is_finite()
&& parsed >= MIN_REFRESH_RATE_HZ
{
return parsed.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
}
if display.is_null() || window == 0 {
return FALLBACK_REFRESH_RATE_HZ;
}
let syms: &LinuxXRandrSyms = linux_xrandr_syms();
if syms.get_screen_info == 0
|| syms.config_current_rate == 0
|| syms.free_screen_config_info == 0
{
return FALLBACK_REFRESH_RATE_HZ;
}
unsafe {
let get_info: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void =
transmute(syms.get_screen_info as *const c_void);
let cur_rate: unsafe extern "C" fn(*mut c_void) -> i16 =
transmute(syms.config_current_rate as *const c_void);
let free_info: unsafe extern "C" fn(*mut c_void) =
transmute(syms.free_screen_config_info as *const c_void);
let config: *mut c_void = get_info(display, window);
if config.is_null() {
return FALLBACK_REFRESH_RATE_HZ;
}
let rate: i16 = cur_rate(config);
free_info(config);
if rate >= 24 {
(rate as f32).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ)
} else {
FALLBACK_REFRESH_RATE_HZ
}
}
}
pub(crate) fn linux_x11_query_scale_factor(display: *mut c_void) -> f32 {
for var_name in LINUX_DPI_ENV_VARS.iter() {
if let Ok(val) = env::var(var_name)
&& let Ok(parsed) = val.trim().parse::<f32>()
&& parsed.is_finite()
&& parsed >= 1.0
{
return parsed.clamp(1.0, 4.0);
}
}
let syms: &LinuxX11Syms = linux_x11_syms();
if syms.resource_manager_string != 0 && !display.is_null() {
unsafe {
let x_rm: unsafe extern "C" fn(*mut c_void) -> *const c_char =
transmute(syms.resource_manager_string as *const c_void);
let raw_ptr: *const c_char = x_rm(display);
if !raw_ptr.is_null()
&& let Ok(text) = CStr::from_ptr(raw_ptr).to_str()
{
for line in text.lines() {
let trimmed: &str = line.trim();
if let Some(rest) = trimmed.strip_prefix(XFT_DPI_PREFIX)
&& let Ok(dpi) = rest.trim().parse::<f32>()
&& dpi.is_finite()
&& dpi > 48.0
{
return (dpi / X11_DEFAULT_DPI).clamp(1.0, 4.0);
}
}
}
}
}
1.0
}
fn linux_x11_probe_mit_shm(display: *mut c_void) -> bool {
let shm: &LinuxXShmSyms = linux_xshm_syms();
if display.is_null()
|| shm.query_extension == 0
|| shm.create_image == 0
|| shm.attach == 0
|| shm.detach == 0
|| shm.put_image == 0
{
return false;
}
unsafe {
let query_fn: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(shm.query_extension as *const c_void);
query_fn(display) != 0
}
}
#[must_use]
fn linux_should_prefer_wayland() -> bool {
if let Ok(force_x11) = env::var(LINUX_FORCE_X11_ENV)
&& force_x11.trim() == "1"
{
return false;
}
env::var(LINUX_WAYLAND_DISPLAY_ENV)
.map(|val: String| !val.trim().is_empty())
.unwrap_or(false)
}
pub(crate) fn linux_create_native_window(
config: &WindowConfig,
) -> Result<LinuxNativeWindowHandle, PlatformError> {
unsafe {
if linux_should_prefer_wayland() {
let wl: &LinuxWaylandSyms = linux_wayland_syms();
if wl.lib != 0 && wl.display_connect != 0 {
let wl_connect: unsafe extern "C" fn(*const c_char) -> *mut c_void =
transmute(wl.display_connect as *const c_void);
let wl_display: *mut c_void = wl_connect(null());
if !wl_display.is_null() {
if wl.display_roundtrip != 0 {
let wl_roundtrip: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(wl.display_roundtrip as *const c_void);
let _: i32 = wl_roundtrip(wl_display);
}
let scale_factor: f32 = linux_x11_query_scale_factor(null_mut());
return Ok(LinuxNativeWindowHandle {
lib: wl.lib,
is_wayland: true,
display: wl_display as usize,
window: 0,
gc: 0,
visual: 0,
depth: 32,
wm_delete_atom: 0,
scale_factor,
mit_shm_available: false,
wayland_vulkan_wsi: wl.vulkan_wsi_available,
});
}
}
}
let x11: &LinuxX11Syms = linux_x11_syms();
if x11.lib != 0
&& x11.open_display != 0
&& x11.default_screen != 0
&& x11.root_window != 0
&& x11.create_simple_window != 0
{
let x_open: unsafe extern "C" fn(*const c_char) -> *mut c_void =
transmute(x11.open_display as *const c_void);
let display: *mut c_void = x_open(null());
if !display.is_null() {
let x_screen: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(x11.default_screen as *const c_void);
let x_root: unsafe extern "C" fn(*mut c_void, i32) -> u64 =
transmute(x11.root_window as *const c_void);
let x_create: unsafe extern "C" fn(
*mut c_void,
u64,
i32,
i32,
u32,
u32,
u32,
u64,
u64,
) -> u64 = transmute(x11.create_simple_window as *const c_void);
let screen: i32 = x_screen(display);
let root: u64 = x_root(display, screen);
let scale_factor: f32 = linux_x11_query_scale_factor(display);
let phys_w: u32 = ((config.get_width() as f32) * scale_factor)
.round()
.max(1.0) as u32;
let phys_h: u32 = ((config.get_height() as f32) * scale_factor)
.round()
.max(1.0) as u32;
let (pos_x, pos_y): (i32, i32) = config.position_value().unwrap_or((0, 0));
let win: u64 = x_create(display, root, pos_x, pos_y, phys_w, phys_h, 0, 0, 0);
let gc: usize = if x11.default_gc != 0 {
let x_gc: unsafe extern "C" fn(*mut c_void, i32) -> *mut c_void =
transmute(x11.default_gc as *const c_void);
x_gc(display, screen) as usize
} else {
0
};
let visual: usize = if x11.default_visual != 0 {
let x_vis: unsafe extern "C" fn(*mut c_void, i32) -> *mut c_void =
transmute(x11.default_visual as *const c_void);
x_vis(display, screen) as usize
} else {
0
};
let depth: u32 = if x11.default_depth != 0 {
let x_dep: unsafe extern "C" fn(*mut c_void, i32) -> i32 =
transmute(x11.default_depth as *const c_void);
x_dep(display, screen).max(24) as u32
} else {
24
};
if x11.select_input != 0 {
let x_select: unsafe extern "C" fn(*mut c_void, u64, isize) -> i32 =
transmute(x11.select_input as *const c_void);
let _: i32 = x_select(display, win, X11_EVENT_MASK);
}
let mut wm_delete_atom: u64 = 0;
if x11.intern_atom != 0 && x11.set_wm_protocols != 0 {
let x_intern: unsafe extern "C" fn(*mut c_void, *const c_char, i32) -> u64 =
transmute(x11.intern_atom as *const c_void);
let x_proto: unsafe extern "C" fn(*mut c_void, u64, *mut u64, i32) -> i32 =
transmute(x11.set_wm_protocols as *const c_void);
wm_delete_atom =
x_intern(display, ATOM_WM_DELETE_WINDOW.as_ptr().cast::<c_char>(), 0);
if wm_delete_atom != 0 {
let _: i32 = x_proto(display, win, &mut wm_delete_atom, 1);
}
}
if x11.store_name != 0
&& let Ok(c_title) = CString::new(config.get_title().as_str())
{
let x_store: unsafe extern "C" fn(*mut c_void, u64, *const c_char) -> i32 =
transmute(x11.store_name as *const c_void);
let _: i32 = x_store(display, win, c_title.as_ptr());
}
if x11.flush != 0 {
let x_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(x11.flush as *const c_void);
let _: i32 = x_flush(display);
}
let mit_shm_available: bool = linux_x11_probe_mit_shm(display);
return Ok(LinuxNativeWindowHandle {
lib: x11.lib,
is_wayland: false,
display: display as usize,
window: win,
gc,
visual,
depth,
wm_delete_atom,
scale_factor,
mit_shm_available,
wayland_vulkan_wsi: false,
});
}
}
let wl: &LinuxWaylandSyms = linux_wayland_syms();
if wl.lib != 0 && wl.display_connect != 0 {
let wl_connect: unsafe extern "C" fn(*const c_char) -> *mut c_void =
transmute(wl.display_connect as *const c_void);
let wl_display: *mut c_void = wl_connect(null());
if !wl_display.is_null() {
return Ok(LinuxNativeWindowHandle {
lib: wl.lib,
is_wayland: true,
display: wl_display as usize,
window: 0,
gc: 0,
visual: 0,
depth: 32,
wm_delete_atom: 0,
scale_factor: linux_x11_query_scale_factor(null_mut()),
mit_shm_available: false,
wayland_vulkan_wsi: wl.vulkan_wsi_available,
});
}
}
}
Err(PlatformError::InitializationFailed(
ERR_LINUX_NO_DISPLAY.to_string(),
))
}
pub(crate) fn linux_x11_map_window(display: usize, window: u64) {
if display == 0 || window == 0 {
return;
}
let syms: &LinuxX11Syms = linux_x11_syms();
if syms.map_window == 0 {
return;
}
unsafe {
let x_map: unsafe extern "C" fn(*mut c_void, u64) -> i32 =
transmute(syms.map_window as *const c_void);
let _: i32 = x_map(display as *mut c_void, window);
if syms.flush != 0 {
let x_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(syms.flush as *const c_void);
let _: i32 = x_flush(display as *mut c_void);
}
}
}
fn linux_pack_bgra_subrect(
framebuffer: &Framebuffer,
x0: u32,
y0: u32,
width: u32,
height: u32,
) -> Vec<u8> {
let fb_w: usize = framebuffer.get_width() as usize;
let src: &[u8] = framebuffer.get_pixels().as_slice();
let mut bgra: Vec<u8> = Vec::with_capacity((width as usize) * (height as usize) * 4);
for row in y0..(y0 + height) {
let row_start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
let row_end: usize = row_start + (width as usize) * 4;
if row_end <= src.len() {
for px in src[row_start..row_end].as_chunks::<4>().0 {
bgra.push(px[2]);
bgra.push(px[1]);
bgra.push(px[0]);
bgra.push(px[3]);
}
}
}
bgra
}
pub(crate) fn linux_x11_present_framebuffer(
rec: &LinuxWindowRecord,
framebuffer: &Framebuffer,
dirty_rect: Option<Rect>,
) -> Result<(), PlatformError> {
if rec.get_is_wayland() {
let wl: &LinuxWaylandSyms = linux_wayland_syms();
if rec.get_display() != 0 && wl.display_flush != 0 {
unsafe {
let wl_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(wl.display_flush as *const c_void);
let _: i32 = wl_flush(rec.get_display() as *mut c_void);
}
}
return Ok(());
}
if rec.get_display() == 0 || rec.get_window() == 0 || rec.get_gc() == 0 || rec.get_visual() == 0
{
return Ok(());
}
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
if fb_w == 0 || fb_h == 0 {
return Ok(());
}
let syms: &LinuxX11Syms = linux_x11_syms();
if syms.create_image == 0 || syms.put_image == 0 {
return Ok(());
}
let (dst_x, dst_y, blit_w, blit_h, mut bgra): (i32, i32, u32, u32, Vec<u8>) = match dirty_rect {
Some(r) => {
let x0: u32 = (r.get_x().floor().max(0.0) as u32).min(fb_w);
let y0: u32 = (r.get_y().floor().max(0.0) as u32).min(fb_h);
let x1: u32 = ((r.get_x() + r.get_width()).ceil().max(0.0) as u32).min(fb_w);
let y1: u32 = ((r.get_y() + r.get_height()).ceil().max(0.0) as u32).min(fb_h);
if x1 > x0 && y1 > y0 && (x1 - x0 < fb_w || y1 - y0 < fb_h) {
let rw: u32 = x1 - x0;
let rh: u32 = y1 - y0;
(
x0 as i32,
y0 as i32,
rw,
rh,
linux_pack_bgra_subrect(framebuffer, x0, y0, rw, rh),
)
} else {
(0, 0, fb_w, fb_h, framebuffer.to_bgra_bytes())
}
}
None => (0, 0, fb_w, fb_h, framebuffer.to_bgra_bytes()),
};
let stride: i32 = (blit_w as i32) * 4;
unsafe {
let x_create_img: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
u32,
i32,
i32,
*mut c_char,
u32,
u32,
i32,
i32,
) -> *mut c_void = transmute(syms.create_image as *const c_void);
let x_put_img: unsafe extern "C" fn(
*mut c_void,
u64,
*mut c_void,
*mut c_void,
i32,
i32,
i32,
i32,
u32,
u32,
) -> i32 = transmute(syms.put_image as *const c_void);
let display: *mut c_void = rec.get_display() as *mut c_void;
let visual: *mut c_void = rec.get_visual() as *mut c_void;
let gc: *mut c_void = rec.get_gc() as *mut c_void;
let img: *mut c_void = x_create_img(
display,
visual,
rec.get_depth(),
X11_Z_PIXMAP,
0,
bgra.as_mut_ptr().cast::<c_char>(),
blit_w,
blit_h,
32,
stride,
);
if !img.is_null() {
let _: i32 = x_put_img(
display,
rec.get_window(),
gc,
img,
0,
0,
dst_x,
dst_y,
blit_w,
blit_h,
);
if syms.free != 0 {
let x_free: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(syms.free as *const c_void);
let _: i32 = x_free(img);
}
}
if syms.flush != 0 {
let x_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(syms.flush as *const c_void);
let _: i32 = x_flush(display);
}
}
Ok(())
}
#[must_use]
fn linux_x11_modifiers(state: u32) -> Modifiers {
Modifiers::new(
(state & X11_SHIFT_MASK) != 0,
(state & X11_CTRL_MASK) != 0,
(state & X11_ALT_MASK) != 0,
(state & X11_META_MASK) != 0,
)
}
#[must_use]
fn linux_x11_keysym_to_keycode(keysym: u64, ch: Option<char>) -> KeyCode {
match keysym {
0xFF08 => KeyCode::Backspace,
0xFF09 => KeyCode::Tab,
0xFF0D | 0xFF8D => KeyCode::Enter,
0xFF1B => KeyCode::Escape,
0xFF50 => KeyCode::Home,
0xFF51 => KeyCode::ArrowLeft,
0xFF52 => KeyCode::ArrowUp,
0xFF53 => KeyCode::ArrowRight,
0xFF54 => KeyCode::ArrowDown,
0xFF55 => KeyCode::PageUp,
0xFF56 => KeyCode::PageDown,
0xFF57 => KeyCode::End,
0xFFFF => KeyCode::Delete,
0x0020 => KeyCode::Space,
0x0021..=0x007E => KeyCode::Character((keysym as u8 as char).to_ascii_lowercase()),
_ => match ch {
Some(c) if !c.is_control() => KeyCode::Character(c),
_ => KeyCode::Unknown,
},
}
}
#[must_use]
fn linux_find_window(
xid: u64,
map: &HashMap<WindowId, LinuxWindowRecord>,
) -> Option<(WindowId, f32, u64)> {
for (wid, rec) in map.iter() {
if !rec.get_is_wayland() && rec.get_window() == xid {
return Some((
*wid,
rec.get_state().get_scale_factor(),
rec.get_wm_delete_atom(),
));
}
}
None
}
unsafe fn linux_x11_handle_raw_event(
raw: &X11EventRaw,
lookup_sym: *mut c_void,
windows: &mut HashMap<WindowId, LinuxWindowRecord>,
out_events: &mut Vec<WindowEvent>,
) {
let ev_type: i32 = (raw.pad[0] & 0xFFFF_FFFF) as i32;
unsafe {
match ev_type {
X11_CONFIGURE_NOTIFY => {
let cfg_ev: X11ConfigureEvent =
*(raw as *const X11EventRaw).cast::<X11ConfigureEvent>();
if let Some((wid, scale, _)) = linux_find_window(cfg_ev.window, windows) {
let phys_w: u32 = cfg_ev.width.max(1) as u32;
let phys_h: u32 = cfg_ev.height.max(1) as u32;
let exact_lw: f32 = ((phys_w as f32) / scale).max(1.0);
let exact_lh: f32 = ((phys_h as f32) / scale).max(1.0);
let log_w: u32 = exact_lw.round().max(1.0) as u32;
let log_h: u32 = exact_lh.round().max(1.0) as u32;
if let Some(rec) = windows.get_mut(&wid) {
let prev_w: u32 = rec.get_state().get_physical_width();
let prev_h: u32 = rec.get_state().get_physical_height();
if prev_w != phys_w || prev_h != phys_h {
rec.get_mut_config().set_width(log_w);
rec.get_mut_config().set_height(log_h);
rec.get_mut_state().set_logical_width(exact_lw);
rec.get_mut_state().set_logical_height(exact_lh);
rec.get_mut_state().set_physical_width(phys_w);
rec.get_mut_state().set_physical_height(phys_h);
out_events.push(WindowEvent::Resized(wid, log_w, log_h, scale));
}
}
}
}
X11_EXPOSE => {
let kb: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if let Some((wid, _, _)) = linux_find_window(kb.window, windows) {
out_events.push(WindowEvent::RedrawRequested(wid));
}
}
X11_CLIENT_MESSAGE => {
let cm: X11ClientMessageEvent =
*(raw as *const X11EventRaw).cast::<X11ClientMessageEvent>();
if let Some((wid, _, wm_del)) = linux_find_window(cm.window, windows)
&& wm_del != 0
&& cm.data[0] == wm_del
{
out_events.push(WindowEvent::CloseRequested(wid));
}
}
X11_FOCUS_IN | X11_FOCUS_OUT => {
let kb: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if let Some((wid, _, _)) = linux_find_window(kb.window, windows) {
let focused: bool = ev_type == X11_FOCUS_IN;
if let Some(rec) = windows.get_mut(&wid) {
rec.get_mut_state().set_focused(focused);
}
if !focused {
out_events.push(WindowEvent::PointerCancel(wid, 0));
}
out_events.push(WindowEvent::Focused(wid, focused));
let lc_ev: SystemEvent = if focused {
SystemEvent::Foreground
} else {
SystemEvent::Inactive
};
out_events.push(WindowEvent::System(lc_ev));
}
}
X11_UNMAP_NOTIFY => {
let kb: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if let Some((wid, _, _)) = linux_find_window(kb.window, windows) {
out_events.push(WindowEvent::PointerCancel(wid, 0));
out_events.push(WindowEvent::System(SystemEvent::Background));
}
}
X11_MAP_NOTIFY => {
let kb: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if linux_find_window(kb.window, windows).is_some() {
out_events.push(WindowEvent::System(SystemEvent::Foreground));
}
}
X11_DESTROY_NOTIFY => {
let kb: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if linux_find_window(kb.window, windows).is_some() {
out_events.push(WindowEvent::System(SystemEvent::Terminate));
}
}
X11_MOTION_NOTIFY => {
let mot: X11MotionEvent = *(raw as *const X11EventRaw).cast::<X11MotionEvent>();
if let Some((wid, scale, _)) = linux_find_window(mot.window, windows) {
let pos: Point = Point::new((mot.x as f32) / scale, (mot.y as f32) / scale);
let pressed_btn: f32 = if (mot.state & 0x0100) != 0 { 1.0 } else { 0.0 };
let ev: PointerEvent = PointerEvent::new(
1,
PointerDevice::Mouse,
pos,
PointerButton::Primary,
pressed_btn,
linux_x11_modifiers(mot.state),
);
out_events.push(WindowEvent::PointerMove(wid, ev));
}
}
X11_BUTTON_PRESS | X11_BUTTON_RELEASE => {
let btn: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if let Some((wid, scale, _)) = linux_find_window(btn.window, windows) {
if ev_type == X11_BUTTON_PRESS && (btn.detail == 4 || btn.detail == 5) {
let step: f32 = if btn.detail == 4 { -40.0 } else { 40.0 };
let delta: Point = if (btn.state & X11_SHIFT_MASK) != 0 {
Point::new(step, 0.0)
} else {
Point::new(0.0, step)
};
out_events.push(WindowEvent::Scroll(wid, delta));
} else if ev_type == X11_BUTTON_PRESS && (btn.detail == 6 || btn.detail == 7) {
let dx: f32 = if btn.detail == 6 { -40.0 } else { 40.0 };
out_events.push(WindowEvent::Scroll(wid, Point::new(dx, 0.0)));
} else if btn.detail <= 3 {
let button: PointerButton = match btn.detail {
2 => PointerButton::Auxiliary,
3 => PointerButton::Secondary,
_ => PointerButton::Primary,
};
let pos: Point = Point::new((btn.x as f32) / scale, (btn.y as f32) / scale);
let pressed: bool = ev_type == X11_BUTTON_PRESS;
let pev: PointerEvent = PointerEvent::new(
1,
PointerDevice::Mouse,
pos,
button,
if pressed { 1.0 } else { 0.0 },
linux_x11_modifiers(btn.state),
);
if pressed {
out_events.push(WindowEvent::PointerDown(wid, pev));
} else {
out_events.push(WindowEvent::PointerUp(wid, pev));
}
}
}
}
X11_KEY_PRESS | X11_KEY_RELEASE => {
let mut key_ev: X11KeyOrButtonEvent =
*(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
if let Some((wid, _, _)) = linux_find_window(key_ev.window, windows) {
let mut buf: [u8; 16] = [0; 16];
let mut keysym: u64 = 0;
let mut len: i32 = 0;
if !lookup_sym.is_null() {
let lookup_fn: unsafe extern "C" fn(
*mut X11KeyOrButtonEvent,
*mut c_char,
i32,
*mut u64,
*mut c_void,
) -> i32 = transmute(lookup_sym);
len = lookup_fn(
&mut key_ev,
buf.as_mut_ptr().cast::<c_char>(),
16,
&mut keysym,
null_mut(),
);
}
let decoded_str: Option<&str> = if len > 0 {
from_utf8(&buf[..(len as usize).min(16)]).ok()
} else {
None
};
let first_ch: Option<char> = decoded_str.and_then(|s: &str| s.chars().next());
let code: KeyCode = linux_x11_keysym_to_keycode(keysym, first_ch);
let mods: Modifiers = linux_x11_modifiers(key_ev.state);
let kev: KeyEvent = KeyEvent::new(code, mods, false);
if ev_type == X11_KEY_PRESS {
out_events.push(WindowEvent::KeyDown(wid, kev));
if !mods.get_ctrl()
&& !mods.get_meta()
&& let Some(text) = decoded_str
&& text.chars().all(|c: char| !c.is_control())
&& !text.is_empty()
{
out_events.push(WindowEvent::TextInput(wid, text.to_string()));
}
} else {
out_events.push(WindowEvent::KeyUp(wid, kev));
}
}
}
_ => {}
}
}
}
pub(crate) fn linux_x11_pump_events(
windows: &mut HashMap<WindowId, LinuxWindowRecord>,
out_events: &mut Vec<WindowEvent>,
) {
if windows.is_empty() {
return;
}
let wl: &LinuxWaylandSyms = linux_wayland_syms();
if wl.display_dispatch_pending != 0 {
let mut wl_displays: Vec<usize> = Vec::new();
for rec in windows.values() {
if rec.get_is_wayland()
&& rec.get_display() != 0
&& !wl_displays.contains(&rec.get_display())
{
wl_displays.push(rec.get_display());
}
}
unsafe {
let wl_dispatch_pending: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(wl.display_dispatch_pending as *const c_void);
for disp in wl_displays.into_iter() {
let _: i32 = wl_dispatch_pending(disp as *mut c_void);
}
}
}
let syms: &LinuxX11Syms = linux_x11_syms();
if syms.pending == 0 || syms.next_event == 0 {
return;
}
let displays: Vec<usize> = {
let mut seen: Vec<usize> = Vec::new();
for rec in windows.values() {
if !rec.get_is_wayland() && rec.get_display() != 0 && !seen.contains(&rec.get_display())
{
seen.push(rec.get_display());
}
}
seen
};
let lookup_sym: *mut c_void = syms.lookup_string as *mut c_void;
unsafe {
let x_pending: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(syms.pending as *const c_void);
let x_next: unsafe extern "C" fn(*mut c_void, *mut X11EventRaw) -> i32 =
transmute(syms.next_event as *const c_void);
for disp_addr in displays.into_iter() {
let disp: *mut c_void = disp_addr as *mut c_void;
let mut raw: X11EventRaw = X11EventRaw { pad: [0; 24] };
while x_pending(disp) > 0 {
let _: i32 = x_next(disp, &mut raw);
linux_x11_handle_raw_event(&raw, lookup_sym, windows, out_events);
}
}
}
}
pub(crate) fn linux_x11_wait_events(
windows: &mut HashMap<WindowId, LinuxWindowRecord>,
out_events: &mut Vec<WindowEvent>,
) {
if windows.is_empty() {
return;
}
if let Some(wl_disp) = windows
.values()
.find(|rec: &&LinuxWindowRecord| rec.get_is_wayland() && rec.get_display() != 0)
.map(LinuxWindowRecord::get_display)
{
let wl: &LinuxWaylandSyms = linux_wayland_syms();
if wl.display_dispatch != 0 {
unsafe {
let wl_dispatch: unsafe extern "C" fn(*mut c_void) -> i32 =
transmute(wl.display_dispatch as *const c_void);
let _: i32 = wl_dispatch(wl_disp as *mut c_void);
}
}
return;
}
let first_disp: usize = windows
.values()
.find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland() && rec.get_display() != 0)
.map(LinuxWindowRecord::get_display)
.unwrap_or(0);
if first_disp == 0 {
return;
}
let syms: &LinuxX11Syms = linux_x11_syms();
if syms.next_event == 0 {
return;
}
let lookup_sym: *mut c_void = syms.lookup_string as *mut c_void;
unsafe {
let x_next: unsafe extern "C" fn(*mut c_void, *mut X11EventRaw) -> i32 =
transmute(syms.next_event as *const c_void);
let mut raw: X11EventRaw = X11EventRaw { pad: [0; 24] };
let _: i32 = x_next(first_disp as *mut c_void, &mut raw);
linux_x11_handle_raw_event(&raw, lookup_sym, windows, out_events);
}
linux_x11_pump_events(windows, out_events);
}
pub(crate) fn linux_wayland_disconnect(display: usize) {
if display == 0 {
return;
}
let wl: &LinuxWaylandSyms = linux_wayland_syms();
if wl.display_disconnect == 0 {
return;
}
unsafe {
let disconnect: unsafe extern "C" fn(*mut c_void) =
transmute(wl.display_disconnect as *const c_void);
disconnect(display as *mut c_void);
}
}
pub(crate) fn linux_x11_set_title(display: usize, window: u64, title: &str) {
let syms: &LinuxX11Syms = linux_x11_syms();
if display == 0 || window == 0 || syms.store_name == 0 {
return;
}
if let Ok(c_title) = CString::new(title) {
unsafe {
let func: unsafe extern "C" fn(*mut c_void, u64, *const c_char) -> i32 =
transmute(syms.store_name as *const c_void);
let _: i32 = func(display as *mut c_void, window, c_title.as_ptr());
}
}
}
pub(crate) fn linux_x11_resize(display: usize, window: u64, width: u32, height: u32) {
let syms: &LinuxX11Syms = linux_x11_syms();
if display == 0 || window == 0 || syms.resize_window == 0 {
return;
}
unsafe {
let func: unsafe extern "C" fn(*mut c_void, u64, u32, u32) -> i32 =
transmute(syms.resize_window as *const c_void);
let _: i32 = func(display as *mut c_void, window, width.max(1), height.max(1));
}
}
pub(crate) fn linux_x11_destroy(display: usize, window: u64) {
let syms: &LinuxX11Syms = linux_x11_syms();
if display == 0 || window == 0 || syms.destroy_window == 0 {
return;
}
unsafe {
let func: unsafe extern "C" fn(*mut c_void, u64) -> i32 =
transmute(syms.destroy_window as *const c_void);
let _: i32 = func(display as *mut c_void, window);
}
}