Skip to main content

strata_platform/
x11_window.rs

1//! Pure-Rust Linux X11 Windowing, Event Loop, and MIT-SHM Shared Memory Presentation.
2//!
3//! Provides zero-dependency native X11 wire protocol communication over `/tmp/.X11-unix/X0`,
4//! hardware event decoding, POSIX/SysV shared memory surface presentation (`MIT-SHM`),
5//! and legacy xlib compatibility fallback.
6
7#![cfg(target_os = "linux")]
8
9use std::collections::VecDeque;
10use std::io::{Read, Write};
11use std::os::unix::net::UnixStream;
12use std::time::Duration;
13
14#[cfg(feature = "xlib")]
15use std::ffi::CString;
16#[cfg(feature = "xlib")]
17use std::os::raw::{c_char, c_int, c_ulong};
18#[cfg(feature = "xlib")]
19use x11::xlib;
20
21use crate::events::{KeyCode, Modifiers, MouseButton, PlatformEvent};
22use crate::surface::PresentError;
23use crate::window::{
24    CursorIcon, EventLoop, EventLoopControl, NativeSurfaceWindow, PlatformWindow, WindowConfig,
25    WindowMode,
26};
27
28// Core X11 Protocol Request Opcodes
29pub const X11_OPCODE_CREATE_WINDOW: u8 = 1;
30pub const X11_OPCODE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2;
31pub const X11_OPCODE_MAP_WINDOW: u8 = 8;
32pub const X11_OPCODE_INTERN_ATOM: u8 = 16;
33pub const X11_OPCODE_CHANGE_PROPERTY: u8 = 18;
34pub const X11_OPCODE_SEND_EVENT: u8 = 25;
35pub const X11_OPCODE_CREATE_GC: u8 = 55;
36pub const X11_OPCODE_PUT_IMAGE: u8 = 72;
37pub const X11_OPCODE_QUERY_EXTENSION: u8 = 98;
38
39// Standard X11 Predefined Atoms
40pub const XA_STRING: u32 = 31;
41pub const XA_WM_NAME: u32 = 39;
42
43// MIT-SHM Extension Request Opcodes (Relative to Extension Major Opcode)
44pub const X11_SHM_OPCODE_ATTACH: u8 = 1;
45pub const X11_SHM_OPCODE_PUT_IMAGE: u8 = 3;
46
47/// Resolves the default X11 UNIX domain socket path from the `$DISPLAY` environment variable.
48pub fn default_x11_socket_path() -> String {
49    let display = std::env::var("DISPLAY").unwrap_or_else(|_| ":0".to_string());
50    let display_num = display
51        .rsplit(':')
52        .next()
53        .unwrap_or("0")
54        .split('.')
55        .next()
56        .unwrap_or("0")
57        .parse::<u32>()
58        .unwrap_or(0);
59    format!("/tmp/.X11-unix/X{}", display_num)
60}
61
62/// Pure-Rust X11 wire protocol request encoder.
63#[derive(Debug, Default)]
64pub struct X11WireEncoder {
65    buffer: Vec<u8>,
66}
67
68impl X11WireEncoder {
69    /// Creates a new encoder with default capacity.
70    pub fn new() -> Self {
71        Self {
72            buffer: Vec::with_capacity(256),
73        }
74    }
75
76    /// Clears the encoder buffer.
77    pub fn clear(&mut self) {
78        self.buffer.clear();
79    }
80
81    /// Returns the encoded byte slice.
82    pub fn as_bytes(&self) -> &[u8] {
83        &self.buffer
84    }
85
86    /// Reserves space for the 4-byte X11 request header: [opcode, detail, len_lo, len_hi].
87    pub fn begin_request(&mut self, opcode: u8, detail: u8) {
88        self.buffer.clear();
89        self.buffer.push(opcode);
90        self.buffer.push(detail);
91        self.buffer.push(0);
92        self.buffer.push(0);
93    }
94
95    /// Finalizes the request header by calculating total length in 4-byte words, padding as needed.
96    pub fn finish_request(&mut self) {
97        while !self.buffer.len().is_multiple_of(4) {
98            self.buffer.push(0);
99        }
100        let len_words = (self.buffer.len() / 4) as u16;
101        let len_bytes = len_words.to_ne_bytes();
102        self.buffer[2] = len_bytes[0];
103        self.buffer[3] = len_bytes[1];
104    }
105
106    /// Appends an 8-bit unsigned integer.
107    pub fn push_u8(&mut self, val: u8) {
108        self.buffer.push(val);
109    }
110
111    /// Appends a 16-bit unsigned integer in native byte order.
112    pub fn push_u16(&mut self, val: u16) {
113        self.buffer.extend_from_slice(&val.to_ne_bytes());
114    }
115
116    /// Appends a 16-bit signed integer in native byte order.
117    pub fn push_i16(&mut self, val: i16) {
118        self.buffer.extend_from_slice(&val.to_ne_bytes());
119    }
120
121    /// Appends a 32-bit unsigned integer in native byte order.
122    pub fn push_u32(&mut self, val: u32) {
123        self.buffer.extend_from_slice(&val.to_ne_bytes());
124    }
125
126    /// Appends arbitrary raw bytes.
127    pub fn push_bytes(&mut self, bytes: &[u8]) {
128        self.buffer.extend_from_slice(bytes);
129    }
130
131    /// Appends a string and aligns the buffer to a 4-byte boundary.
132    pub fn push_padded_string(&mut self, s: &str) {
133        let bytes = s.as_bytes();
134        self.buffer.extend_from_slice(bytes);
135        while !self.buffer.len().is_multiple_of(4) {
136            self.buffer.push(0);
137        }
138    }
139}
140
141/// Pure-Rust X11 wire protocol reply and event decoder.
142#[derive(Debug)]
143pub struct X11WireDecoder<'a> {
144    data: &'a [u8],
145    offset: usize,
146}
147
148impl<'a> X11WireDecoder<'a> {
149    /// Creates a decoder over the given buffer slice.
150    pub fn new(data: &'a [u8]) -> Self {
151        Self { data, offset: 0 }
152    }
153
154    /// Returns the number of remaining bytes.
155    pub fn remaining(&self) -> usize {
156        self.data.len().saturating_sub(self.offset)
157    }
158
159    /// Reads an 8-bit unsigned integer.
160    pub fn read_u8(&mut self) -> Option<u8> {
161        if self.remaining() < 1 {
162            return None;
163        }
164        let val = self.data[self.offset];
165        self.offset += 1;
166        Some(val)
167    }
168
169    /// Reads a 16-bit unsigned integer in native byte order.
170    pub fn read_u16(&mut self) -> Option<u16> {
171        if self.remaining() < 2 {
172            return None;
173        }
174        let val = u16::from_ne_bytes(self.data[self.offset..self.offset + 2].try_into().unwrap());
175        self.offset += 2;
176        Some(val)
177    }
178
179    /// Reads a 16-bit signed integer in native byte order.
180    pub fn read_i16(&mut self) -> Option<i16> {
181        if self.remaining() < 2 {
182            return None;
183        }
184        let val = i16::from_ne_bytes(self.data[self.offset..self.offset + 2].try_into().unwrap());
185        self.offset += 2;
186        Some(val)
187    }
188
189    /// Reads a 32-bit unsigned integer in native byte order.
190    pub fn read_u32(&mut self) -> Option<u32> {
191        if self.remaining() < 4 {
192            return None;
193        }
194        let val = u32::from_ne_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
195        self.offset += 4;
196        Some(val)
197    }
198
199    /// Reads `n` raw bytes.
200    pub fn read_bytes(&mut self, n: usize) -> Option<&'a [u8]> {
201        if self.remaining() < n {
202            return None;
203        }
204        let slice = &self.data[self.offset..self.offset + n];
205        self.offset += n;
206        Some(slice)
207    }
208}
209
210/// Discovered display server properties extracted from initial X11 connection setup reply.
211#[derive(Debug, Clone)]
212pub struct X11ServerInfo {
213    pub resource_id_base: u32,
214    pub resource_id_mask: u32,
215    pub root_window: u32,
216    pub root_visual: u32,
217    pub root_depth: u8,
218    pub black_pixel: u32,
219    pub white_pixel: u32,
220    pub width_in_pixels: u16,
221    pub height_in_pixels: u16,
222}
223
224/// SysV Shared Memory Segment backing MIT-SHM zero-copy presentation.
225pub struct X11ShmSegment {
226    pub shmid: libc::c_int,
227    pub shmseg_id: u32,
228    pub size: usize,
229    pub ptr: *mut u8,
230}
231
232impl X11ShmSegment {
233    /// Allocates and maps a new shared memory segment.
234    pub fn new(shmseg_id: u32, size: usize) -> Result<Self, String> {
235        unsafe {
236            let shmid = libc::shmget(libc::IPC_PRIVATE, size, libc::IPC_CREAT | 0o777);
237            if shmid < 0 {
238                return Err(format!(
239                    "shmget allocation failed: {}",
240                    std::io::Error::last_os_error()
241                ));
242            }
243
244            let ptr = libc::shmat(shmid, std::ptr::null(), 0);
245            if ptr == -1isize as *mut libc::c_void {
246                libc::shmctl(shmid, libc::IPC_RMID, std::ptr::null_mut());
247                return Err(format!(
248                    "shmat mapping failed: {}",
249                    std::io::Error::last_os_error()
250                ));
251            }
252
253            // Immediately mark for removal on disconnect so resources are automatically reclaimed
254            libc::shmctl(shmid, libc::IPC_RMID, std::ptr::null_mut());
255
256            Ok(Self {
257                shmid,
258                shmseg_id,
259                size,
260                ptr: ptr as *mut u8,
261            })
262        }
263    }
264
265    /// Copies a slice of BGRA8 pixel bytes into the shared memory buffer.
266    pub fn write_pixels(&mut self, pixels: &[u8]) {
267        let copy_len = pixels.len().min(self.size);
268        unsafe {
269            std::ptr::copy_nonoverlapping(pixels.as_ptr(), self.ptr, copy_len);
270        }
271    }
272}
273
274impl Drop for X11ShmSegment {
275    fn drop(&mut self) {
276        unsafe {
277            libc::shmdt(self.ptr as *const libc::c_void);
278        }
279    }
280}
281
282/// Pure-Rust X11 client connection manager communicating directly over UNIX domain sockets.
283pub struct PureX11Client {
284    pub stream: UnixStream,
285    pub info: X11ServerInfo,
286    pub next_resource_id: u32,
287    pub mit_shm_opcode: Option<u8>,
288    pub read_buffer: Vec<u8>,
289    pub encoder: X11WireEncoder,
290}
291
292impl PureX11Client {
293    /// Establishes connection to the active X server and performs the protocol handshake.
294    pub fn connect(socket_path: &str) -> Result<Self, String> {
295        let mut stream = UnixStream::connect(socket_path)
296            .map_err(|e| format!("Cannot connect to X11 socket \"{}\": {}", socket_path, e))?;
297
298        // 1. Connection setup packet (12 bytes)
299        // Little-endian byte-order: 'l' (0x6C)
300        let mut setup_packet = [0u8; 12];
301        setup_packet[0] = b'l';
302        setup_packet[2..4].copy_from_slice(&11u16.to_ne_bytes()); // X11 Major Version
303        setup_packet[4..6].copy_from_slice(&0u16.to_ne_bytes()); // Minor Version
304        stream
305            .write_all(&setup_packet)
306            .map_err(|e| format!("Failed to send X11 connection setup: {}", e))?;
307
308        // 2. Read setup reply header (8 bytes)
309        let mut reply_header = [0u8; 8];
310        stream
311            .read_exact(&mut reply_header)
312            .map_err(|e| format!("Failed to read X11 setup reply header: {}", e))?;
313
314        let status = reply_header[0];
315        let extra_length = u16::from_ne_bytes(reply_header[6..8].try_into().unwrap()) as usize * 4;
316
317        let mut extra_data = vec![0u8; extra_length];
318        stream
319            .read_exact(&mut extra_data)
320            .map_err(|e| format!("Failed to read X11 setup extra data: {}", e))?;
321
322        if status != 1 {
323            let reason = String::from_utf8_lossy(&extra_data);
324            return Err(format!("X11 server refused connection: {}", reason));
325        }
326
327        let info = Self::parse_setup_reply(&extra_data)?;
328
329        stream
330            .set_nonblocking(true)
331            .map_err(|e| format!("Failed to set nonblocking stream: {}", e))?;
332
333        let mut client = Self {
334            stream,
335            info,
336            next_resource_id: 0,
337            mit_shm_opcode: None,
338            read_buffer: Vec::with_capacity(4096),
339            encoder: X11WireEncoder::new(),
340        };
341
342        // Query MIT-SHM extension
343        client.mit_shm_opcode = client.query_extension("MIT-SHM").ok().flatten();
344
345        Ok(client)
346    }
347
348    /// Parses the variable-length setup reply extra data into `X11ServerInfo`.
349    fn parse_setup_reply(data: &[u8]) -> Result<X11ServerInfo, String> {
350        if data.len() < 32 {
351            return Err("Setup reply payload too short".to_string());
352        }
353
354        let mut decoder = X11WireDecoder::new(data);
355        let _release = decoder.read_u32().unwrap();
356        let resource_id_base = decoder.read_u32().unwrap();
357        let resource_id_mask = decoder.read_u32().unwrap();
358        let _motion_buffer_size = decoder.read_u32().unwrap();
359        let vendor_len = decoder.read_u16().unwrap() as usize;
360        let _max_req_len = decoder.read_u16().unwrap();
361        let _num_screens = decoder.read_u8().unwrap();
362        let num_formats = decoder.read_u8().unwrap() as usize;
363
364        // Skip image formats and keycodes (10 bytes)
365        let _ = decoder.read_bytes(10);
366
367        // Skip vendor string padded to 4 bytes
368        let vendor_padded = (vendor_len + 3) & !3;
369        let _ = decoder.read_bytes(vendor_padded);
370
371        // Skip formats (8 bytes each)
372        let formats_len = num_formats * 8;
373        let _ = decoder.read_bytes(formats_len);
374
375        // Read Screen 0
376        let root_window = decoder
377            .read_u32()
378            .ok_or_else(|| "Failed to read root window ID".to_string())?;
379        let _default_colormap = decoder.read_u32();
380        let white_pixel = decoder.read_u32().unwrap_or(0xFFFFFF);
381        let black_pixel = decoder.read_u32().unwrap_or(0x000000);
382        let _current_input_masks = decoder.read_u32();
383        let width_in_pixels = decoder.read_u16().unwrap_or(1920);
384        let height_in_pixels = decoder.read_u16().unwrap_or(1080);
385        let _width_in_mm = decoder.read_u16();
386        let _height_in_mm = decoder.read_u16();
387        let _min_maps = decoder.read_u16();
388        let _max_maps = decoder.read_u16();
389        let root_visual = decoder.read_u32().unwrap_or(0);
390        let _backing_stores = decoder.read_u8();
391        let _save_unders = decoder.read_u8();
392        let root_depth = decoder.read_u8().unwrap_or(24);
393
394        Ok(X11ServerInfo {
395            resource_id_base,
396            resource_id_mask,
397            root_window,
398            root_visual,
399            root_depth,
400            black_pixel,
401            white_pixel,
402            width_in_pixels,
403            height_in_pixels,
404        })
405    }
406
407    /// Allocates a unique X11 resource ID.
408    pub fn allocate_id(&mut self) -> u32 {
409        let id = self.info.resource_id_base | (self.next_resource_id & self.info.resource_id_mask);
410        self.next_resource_id += 1;
411        id
412    }
413
414    /// Sends current encoder contents down the socket.
415    pub fn flush_encoder(&mut self) -> Result<(), String> {
416        let bytes = self.encoder.as_bytes();
417        self.stream
418            .write_all(bytes)
419            .map_err(|e| format!("X11 socket write error: {}", e))?;
420        self.encoder.clear();
421        Ok(())
422    }
423
424    /// Queries the server for an extension by name.
425    pub fn query_extension(&mut self, name: &str) -> Result<Option<u8>, String> {
426        self.encoder.begin_request(X11_OPCODE_QUERY_EXTENSION, 0);
427        self.encoder.push_u16(name.len() as u16);
428        self.encoder.push_u16(0); // Pad
429        self.encoder.push_padded_string(name);
430        self.encoder.finish_request();
431        self.flush_encoder()?;
432
433        // Read 32-byte reply
434        let mut reply = [0u8; 32];
435        let mut bytes_read = 0;
436        let start = std::time::Instant::now();
437        while bytes_read < 32 {
438            if start.elapsed() > Duration::from_millis(500) {
439                return Ok(None);
440            }
441            match self.stream.read(&mut reply[bytes_read..]) {
442                Ok(0) => return Err("Server closed socket while querying extension".to_string()),
443                Ok(n) => bytes_read += n,
444                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
445                    std::thread::sleep(Duration::from_millis(1));
446                }
447                Err(e) => return Err(format!("Error reading extension reply: {}", e)),
448            }
449        }
450
451        let present = reply[8];
452        if present == 1 {
453            let major_opcode = reply[9];
454            Ok(Some(major_opcode))
455        } else {
456            Ok(None)
457        }
458    }
459
460    /// Sends a `CreateWindow` request.
461    pub fn create_window(
462        &mut self,
463        window_id: u32,
464        parent: u32,
465        width: u16,
466        height: u16,
467    ) -> Result<(), String> {
468        self.encoder.begin_request(X11_OPCODE_CREATE_WINDOW, 0); // depth 0 = copy from parent
469        self.encoder.push_u32(window_id);
470        self.encoder.push_u32(parent);
471        self.encoder.push_i16(0); // x
472        self.encoder.push_i16(0); // y
473        self.encoder.push_u16(width);
474        self.encoder.push_u16(height);
475        self.encoder.push_u16(0); // border width
476        self.encoder.push_u16(1); // class: InputOutput
477        self.encoder.push_u32(0); // visual: CopyFromParent
478
479        // Value mask: CWBackPixel (0x02) | CWEventMask (0x800)
480        let value_mask = 0x0000_0802u32;
481        self.encoder.push_u32(value_mask);
482        self.encoder.push_u32(self.info.black_pixel);
483
484        // Event mask: Exposure | KeyPress | KeyRelease | ButtonPress | ButtonRelease | Enter | Leave | Motion | StructureNotify | FocusChange
485        let event_mask = 0x0022_807Fu32;
486        self.encoder.push_u32(event_mask);
487
488        self.encoder.finish_request();
489        self.flush_encoder()
490    }
491
492    /// Sends a `MapWindow` request to display the window on screen.
493    pub fn map_window(&mut self, window_id: u32) -> Result<(), String> {
494        self.encoder.begin_request(X11_OPCODE_MAP_WINDOW, 0);
495        self.encoder.push_u32(window_id);
496        self.encoder.finish_request();
497        self.flush_encoder()
498    }
499
500    /// Sends a `CreateGC` request for software blitting.
501    pub fn create_gc(&mut self, gc_id: u32, drawable_id: u32) -> Result<(), String> {
502        self.encoder.begin_request(X11_OPCODE_CREATE_GC, 0);
503        self.encoder.push_u32(gc_id);
504        self.encoder.push_u32(drawable_id);
505        self.encoder.push_u32(0); // value mask: none
506        self.encoder.finish_request();
507        self.flush_encoder()
508    }
509
510    /// Sets the window title via `ChangeProperty` (`WM_NAME`).
511    pub fn set_wm_name(&mut self, window_id: u32, title: &str) -> Result<(), String> {
512        self.encoder.begin_request(X11_OPCODE_CHANGE_PROPERTY, 0); // 0 = Replace mode
513        self.encoder.push_u32(window_id);
514        self.encoder.push_u32(XA_WM_NAME);
515        self.encoder.push_u32(XA_STRING);
516        self.encoder.push_u8(8); // format: 8-bit
517        self.encoder.push_u8(0); // pad
518        self.encoder.push_u16(0); // pad
519        self.encoder.push_u32(title.len() as u32);
520        self.encoder.push_padded_string(title);
521        self.encoder.finish_request();
522        self.flush_encoder()
523    }
524
525    /// Attaches a shared memory segment with the X server via `MIT-SHM ShmAttach`.
526    pub fn shm_attach(
527        &mut self,
528        shm_major: u8,
529        shmseg_id: u32,
530        shmid: libc::c_int,
531    ) -> Result<(), String> {
532        self.encoder.begin_request(shm_major, X11_SHM_OPCODE_ATTACH);
533        self.encoder.push_u32(shmseg_id);
534        self.encoder.push_u32(shmid as u32);
535        self.encoder.push_u32(0); // read_only = false
536        self.encoder.finish_request();
537        self.flush_encoder()
538    }
539
540    /// Dispatches a zero-copy blit from shared memory via `MIT-SHM ShmPutImage`.
541    pub fn shm_put_image(
542        &mut self,
543        shm_major: u8,
544        drawable: u32,
545        gc: u32,
546        shmseg: u32,
547        width: u16,
548        height: u16,
549    ) -> Result<(), String> {
550        self.encoder
551            .begin_request(shm_major, X11_SHM_OPCODE_PUT_IMAGE);
552        self.encoder.push_u32(drawable);
553        self.encoder.push_u32(gc);
554        self.encoder.push_u16(width);
555        self.encoder.push_u16(height);
556        self.encoder.push_u16(0); // src_x
557        self.encoder.push_u16(0); // src_y
558        self.encoder.push_u16(width); // src_w
559        self.encoder.push_u16(height); // src_h
560        self.encoder.push_i16(0); // dst_x
561        self.encoder.push_i16(0); // dst_y
562        self.encoder.push_u8(24); // depth
563        self.encoder.push_u8(2); // format: 2 = ZPixmap
564        self.encoder.push_u8(0); // send_event = 0
565        self.encoder.push_u8(0); // bpad
566        self.encoder.push_u32(shmseg);
567        self.encoder.push_u32(0); // offset
568        self.encoder.finish_request();
569        self.flush_encoder()
570    }
571
572    /// Dispatches a streaming pixel blit via standard `PutImage` (ZPixmap).
573    pub fn put_image(
574        &mut self,
575        drawable: u32,
576        gc: u32,
577        width: u16,
578        height: u16,
579        pixels: &[u8],
580    ) -> Result<(), String> {
581        self.encoder.begin_request(X11_OPCODE_PUT_IMAGE, 2); // 2 = ZPixmap
582        self.encoder.push_u32(drawable);
583        self.encoder.push_u32(gc);
584        self.encoder.push_u16(width);
585        self.encoder.push_u16(height);
586        self.encoder.push_i16(0); // dst_x
587        self.encoder.push_i16(0); // dst_y
588        self.encoder.push_u8(0); // left_pad
589        self.encoder.push_u8(24); // depth
590        self.encoder.push_u16(0); // pad
591        self.encoder.push_bytes(pixels);
592        self.encoder.finish_request();
593        self.flush_encoder()
594    }
595
596    /// Queries or registers an interned atom by name.
597    pub fn intern_atom(&mut self, name: &str, only_if_exists: bool) -> Result<u32, String> {
598        self.encoder
599            .begin_request(X11_OPCODE_INTERN_ATOM, if only_if_exists { 1 } else { 0 });
600        self.encoder.push_u16(name.len() as u16);
601        self.encoder.push_u16(0); // Pad
602        self.encoder.push_padded_string(name);
603        self.encoder.finish_request();
604        self.flush_encoder()?;
605
606        let mut reply = [0u8; 32];
607        let mut bytes_read = 0;
608        let start = std::time::Instant::now();
609        while bytes_read < 32 {
610            if start.elapsed() > Duration::from_millis(500) {
611                return Err("Timeout reading InternAtom reply".to_string());
612            }
613            match self.stream.read(&mut reply[bytes_read..]) {
614                Ok(0) => return Err("Server closed socket while reading InternAtom".to_string()),
615                Ok(n) => bytes_read += n,
616                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
617                    std::thread::sleep(Duration::from_millis(1));
618                }
619                Err(e) => return Err(format!("Error reading InternAtom reply: {}", e)),
620            }
621        }
622        if reply[0] != 1 {
623            return Err("InternAtom returned error reply".to_string());
624        }
625        let atom = u32::from_ne_bytes(reply[8..12].try_into().unwrap());
626        Ok(atom)
627    }
628
629    /// Sends a synthetic 32-bit ClientMessage event to a destination window.
630    pub fn send_client_message(
631        &mut self,
632        dest_window: u32,
633        event_mask: u32,
634        target_window: u32,
635        message_type: u32,
636        data: [u32; 5],
637    ) -> Result<(), String> {
638        self.encoder.begin_request(X11_OPCODE_SEND_EVENT, 0); // propagate = false
639        self.encoder.push_u32(dest_window);
640        self.encoder.push_u32(event_mask);
641        // 32-byte ClientMessage packet
642        self.encoder.push_u8(33); // ClientMessage opcode
643        self.encoder.push_u8(32); // 32-bit format
644        self.encoder.push_u16(0); // Sequence number
645        self.encoder.push_u32(target_window);
646        self.encoder.push_u32(message_type);
647        for &d in &data {
648            self.encoder.push_u32(d);
649        }
650        self.encoder.finish_request();
651        self.flush_encoder()
652    }
653}
654
655/// Pure-Rust X11 native desktop window instance with MIT-SHM support.
656pub struct PureX11Window {
657    pub client: PureX11Client,
658    pub window_id: u32,
659    pub gc_id: u32,
660    pub config: WindowConfig,
661    pub scale_factor: f32,
662    pub is_focused: bool,
663    pub cursor: CursorIcon,
664    pub redraw_requested: bool,
665    pub shm: Option<X11ShmSegment>,
666    pub event_queue: VecDeque<PlatformEvent>,
667    pub last_click: Option<(std::time::Instant, f32, f32)>,
668    pub moveresize_atom: Option<u32>,
669}
670
671impl PureX11Window {
672    /// Creates a native pure-Rust X11 window over the default local display socket.
673    pub fn new(config: WindowConfig) -> Result<Self, String> {
674        let socket_path = default_x11_socket_path();
675        Self::connect_to_socket(&socket_path, config)
676    }
677
678    /// Connects to a specific socket path and initializes the window and graphics context.
679    pub fn connect_to_socket(socket_path: &str, config: WindowConfig) -> Result<Self, String> {
680        let mut client = PureX11Client::connect(socket_path)?;
681
682        let window_id = client.allocate_id();
683        let gc_id = client.allocate_id();
684
685        let w = config.width.max(100) as u16;
686        let h = config.height.max(100) as u16;
687
688        client.create_window(window_id, client.info.root_window, w, h)?;
689        client.set_wm_name(window_id, &config.title)?;
690        client.create_gc(gc_id, window_id)?;
691        client.map_window(window_id)?;
692
693        let mut window = Self {
694            client,
695            window_id,
696            gc_id,
697            config,
698            scale_factor: 1.0,
699            is_focused: true,
700            cursor: CursorIcon::Default,
701            redraw_requested: true,
702            shm: None,
703            event_queue: VecDeque::new(),
704            last_click: None,
705            moveresize_atom: None,
706        };
707
708        window.init_shm_buffer(w as u32, h as u32)?;
709        Ok(window)
710    }
711
712    /// Dispatches an EWMH `_NET_WM_MOVERESIZE` client message delegating window drag or resize.
713    pub fn send_moveresize(
714        &mut self,
715        x: f32,
716        y: f32,
717        direction: u32,
718        button: u32,
719    ) -> Result<(), String> {
720        let atom = if let Some(a) = self.moveresize_atom {
721            a
722        } else {
723            let a = self.client.intern_atom("_NET_WM_MOVERESIZE", false)?;
724            self.moveresize_atom = Some(a);
725            a
726        };
727        let root = self.client.info.root_window;
728        let data = [
729            x as u32, y as u32, direction, button, 1, // source indication: normal application
730        ];
731        self.client
732            .send_client_message(root, 0x0018_0000, self.window_id, atom, data)
733    }
734
735    /// Dispatches an EWMH `_NET_WM_STATE` client message for window maximize or restore.
736    pub fn set_wm_state_maximized(&mut self, maximized: bool) -> Result<(), String> {
737        let wm_state = self.client.intern_atom("_NET_WM_STATE", false)?;
738        let max_vert = self
739            .client
740            .intern_atom("_NET_WM_STATE_MAXIMIZED_VERT", false)?;
741        let max_horz = self
742            .client
743            .intern_atom("_NET_WM_STATE_MAXIMIZED_HORZ", false)?;
744        let root = self.client.info.root_window;
745        let action = if maximized { 1u32 } else { 0u32 };
746        let data = [action, max_vert, max_horz, 1, 0];
747        self.client
748            .send_client_message(root, 0x0018_0000, self.window_id, wm_state, data)
749    }
750
751    /// Allocates or resizes the shared memory segment if MIT-SHM is supported.
752    fn init_shm_buffer(&mut self, width: u32, height: u32) -> Result<(), String> {
753        if let Some(shm_opcode) = self.client.mit_shm_opcode {
754            let shmseg_id = self.client.allocate_id();
755            let size = (width * height * 4) as usize;
756            let shm = X11ShmSegment::new(shmseg_id, size)?;
757            self.client.shm_attach(shm_opcode, shmseg_id, shm.shmid)?;
758            self.shm = Some(shm);
759        }
760        Ok(())
761    }
762
763    /// Presents a BGRA8 pixel buffer directly via MIT-SHM (or streaming PutImage fallback).
764    pub fn present_bgra(
765        &mut self,
766        pixels: &[u8],
767        width: u32,
768        height: u32,
769    ) -> Result<(), PresentError> {
770        if let Some(ref mut shm) = self.shm {
771            if shm.size < (width * height * 4) as usize {
772                let _ = self.init_shm_buffer(width, height);
773            }
774        }
775
776        if let (Some(shm_opcode), Some(ref mut shm)) =
777            (self.client.mit_shm_opcode, self.shm.as_mut())
778        {
779            shm.write_pixels(pixels);
780            self.client
781                .shm_put_image(
782                    shm_opcode,
783                    self.window_id,
784                    self.gc_id,
785                    shm.shmseg_id,
786                    width as u16,
787                    height as u16,
788                )
789                .map_err(PresentError::Custom)?;
790        } else {
791            self.client
792                .put_image(
793                    self.window_id,
794                    self.gc_id,
795                    width as u16,
796                    height as u16,
797                    pixels,
798                )
799                .map_err(PresentError::Custom)?;
800        }
801
802        self.redraw_requested = false;
803        Ok(())
804    }
805
806    /// Reads pending 32-byte event packets from the socket and translates them into PlatformEvents.
807    pub fn poll_native_events(&mut self) -> Vec<PlatformEvent> {
808        let mut chunk = [0u8; 4096];
809        loop {
810            match self.client.stream.read(&mut chunk) {
811                Ok(0) => break,
812                Ok(n) => {
813                    self.client.read_buffer.extend_from_slice(&chunk[..n]);
814                }
815                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
816                Err(_) => break,
817            }
818        }
819
820        // Process 32-byte event packets
821        while self.client.read_buffer.len() >= 32 {
822            let event_bytes = self.client.read_buffer.drain(..32).collect::<Vec<u8>>();
823            self.handle_32_byte_event(&event_bytes);
824        }
825
826        let mut events = Vec::new();
827        while let Some(ev) = self.event_queue.pop_front() {
828            events.push(ev);
829        }
830        events
831    }
832
833    /// Decodes a single 32-byte X11 event packet into platform events.
834    pub fn handle_32_byte_event(&mut self, pkt: &[u8]) {
835        let code = pkt[0] & 0x7F;
836        match code {
837            // Expose (12)
838            12 => {
839                self.redraw_requested = true;
840            }
841            // ConfigureNotify (22)
842            22 => {
843                if pkt.len() >= 24 {
844                    let w = u16::from_ne_bytes(pkt[20..22].try_into().unwrap()) as u32;
845                    let h = u16::from_ne_bytes(pkt[22..24].try_into().unwrap()) as u32;
846                    if w != self.config.width || h != self.config.height {
847                        self.config.width = w;
848                        self.config.height = h;
849                        self.redraw_requested = true;
850                        self.event_queue.push_back(PlatformEvent::WindowResized {
851                            width: w,
852                            height: h,
853                        });
854                    }
855                }
856            }
857            // ButtonPress (4)
858            4 => {
859                let button_num = pkt[1];
860                let x = i16::from_ne_bytes(pkt[24..26].try_into().unwrap()) as f32;
861                let y = i16::from_ne_bytes(pkt[26..28].try_into().unwrap()) as f32;
862                match button_num {
863                    1 => {
864                        let now = std::time::Instant::now();
865                        if let Some((prev_time, px, py)) = self.last_click {
866                            if now.duration_since(prev_time).as_millis() < 400
867                                && (px - x).abs() < 6.0
868                                && (py - y).abs() < 6.0
869                            {
870                                self.event_queue.push_back(PlatformEvent::DoubleClick {
871                                    button: MouseButton::Left,
872                                    x,
873                                    y,
874                                });
875                                self.last_click = None;
876                            } else {
877                                self.last_click = Some((now, x, y));
878                            }
879                        } else {
880                            self.last_click = Some((now, x, y));
881                        }
882                        self.event_queue.push_back(PlatformEvent::MouseDown {
883                            button: MouseButton::Left,
884                            x,
885                            y,
886                        });
887                    }
888                    2 => self.event_queue.push_back(PlatformEvent::MouseDown {
889                        button: MouseButton::Middle,
890                        x,
891                        y,
892                    }),
893                    3 => self.event_queue.push_back(PlatformEvent::MouseDown {
894                        button: MouseButton::Right,
895                        x,
896                        y,
897                    }),
898                    4 => self.event_queue.push_back(PlatformEvent::Scroll {
899                        delta_x: 0.0,
900                        delta_y: -1.0,
901                        is_momentum: false,
902                    }),
903                    5 => self.event_queue.push_back(PlatformEvent::Scroll {
904                        delta_x: 0.0,
905                        delta_y: 1.0,
906                        is_momentum: false,
907                    }),
908                    6 => self.event_queue.push_back(PlatformEvent::Scroll {
909                        delta_x: -1.0,
910                        delta_y: 0.0,
911                        is_momentum: false,
912                    }),
913                    7 => self.event_queue.push_back(PlatformEvent::Scroll {
914                        delta_x: 1.0,
915                        delta_y: 0.0,
916                        is_momentum: false,
917                    }),
918                    b => self.event_queue.push_back(PlatformEvent::MouseDown {
919                        button: MouseButton::Other(b as u16),
920                        x,
921                        y,
922                    }),
923                }
924            }
925            // ButtonRelease (5)
926            5 => {
927                let button_num = pkt[1];
928                let x = i16::from_ne_bytes(pkt[24..26].try_into().unwrap()) as f32;
929                let y = i16::from_ne_bytes(pkt[26..28].try_into().unwrap()) as f32;
930                let button = match button_num {
931                    1 => MouseButton::Left,
932                    2 => MouseButton::Middle,
933                    3 => MouseButton::Right,
934                    b => MouseButton::Other(b as u16),
935                };
936                self.event_queue
937                    .push_back(PlatformEvent::MouseUp { button, x, y });
938            }
939            // MotionNotify (6)
940            6 => {
941                let x = i16::from_ne_bytes(pkt[24..26].try_into().unwrap()) as f32;
942                let y = i16::from_ne_bytes(pkt[26..28].try_into().unwrap()) as f32;
943                self.event_queue
944                    .push_back(PlatformEvent::MouseMove { x, y });
945            }
946            // EnterNotify (7)
947            7 => {
948                self.is_focused = true;
949                self.event_queue
950                    .push_back(PlatformEvent::WindowFocused(true));
951            }
952            // LeaveNotify (8)
953            8 => {
954                self.is_focused = false;
955                self.event_queue.push_back(PlatformEvent::CursorLeft);
956                self.event_queue
957                    .push_back(PlatformEvent::WindowFocused(false));
958            }
959            // KeyPress (2)
960            2 => {
961                let keycode = pkt[1];
962                let (key, ch) = map_x11_pure_keycode(keycode);
963                self.event_queue.push_back(PlatformEvent::KeyDown {
964                    key,
965                    modifiers: Modifiers::default(),
966                });
967                if let Some(c) = ch {
968                    self.event_queue
969                        .push_back(PlatformEvent::ReceivedCharacter(c));
970                }
971            }
972            // KeyRelease (3)
973            3 => {
974                let keycode = pkt[1];
975                let (key, _) = map_x11_pure_keycode(keycode);
976                self.event_queue.push_back(PlatformEvent::KeyUp {
977                    key,
978                    modifiers: Modifiers::default(),
979                });
980            }
981            // ClientMessage (33)
982            33 => {
983                self.event_queue
984                    .push_back(PlatformEvent::WindowCloseRequested);
985            }
986            _ => {}
987        }
988    }
989}
990
991impl PlatformWindow for PureX11Window {
992    fn title(&self) -> &str {
993        &self.config.title
994    }
995
996    fn set_title(&mut self, title: &str) {
997        self.config.title = title.to_string();
998        let _ = self.client.set_wm_name(self.window_id, title);
999    }
1000
1001    fn size(&self) -> (u32, u32) {
1002        (self.config.width, self.config.height)
1003    }
1004
1005    fn set_size(&mut self, width: u32, height: u32) {
1006        self.config.width = width;
1007        self.config.height = height;
1008        let _ = self.init_shm_buffer(width, height);
1009        self.push_event(PlatformEvent::WindowResized { width, height });
1010    }
1011
1012    fn scale_factor(&self) -> f32 {
1013        self.scale_factor
1014    }
1015
1016    fn set_scale_factor(&mut self, scale_factor: f32) {
1017        self.scale_factor = scale_factor;
1018        self.push_event(PlatformEvent::ScaleFactorChanged { scale_factor });
1019    }
1020
1021    fn mode(&self) -> WindowMode {
1022        self.config.mode
1023    }
1024
1025    fn set_mode(&mut self, mode: WindowMode) {
1026        let prev = self.config.mode;
1027        self.config.mode = mode;
1028        if prev != mode {
1029            self.redraw_requested = true;
1030            let _ = self.set_wm_state_maximized(mode == WindowMode::Maximized);
1031            if mode == WindowMode::Maximized {
1032                self.push_event(PlatformEvent::WindowMaximized(true));
1033            } else if prev == WindowMode::Maximized {
1034                self.push_event(PlatformEvent::WindowMaximized(false));
1035            }
1036        }
1037    }
1038
1039    fn is_focused(&self) -> bool {
1040        self.is_focused
1041    }
1042
1043    fn set_focused(&mut self, focused: bool) {
1044        self.is_focused = focused;
1045        self.push_event(PlatformEvent::WindowFocused(focused));
1046    }
1047
1048    fn cursor(&self) -> CursorIcon {
1049        self.cursor
1050    }
1051
1052    fn set_cursor(&mut self, cursor: CursorIcon) {
1053        self.cursor = cursor;
1054    }
1055
1056    fn request_redraw(&mut self) {
1057        self.redraw_requested = true;
1058    }
1059
1060    fn is_redraw_requested(&self) -> bool {
1061        self.redraw_requested
1062    }
1063
1064    fn poll_events(&mut self) -> Vec<PlatformEvent> {
1065        self.poll_native_events()
1066    }
1067
1068    fn push_event(&mut self, event: PlatformEvent) {
1069        self.event_queue.push_back(event);
1070    }
1071
1072    fn begin_window_drag(&mut self, x: f32, y: f32) {
1073        let _ = self.send_moveresize(x, y, 8, 1);
1074    }
1075
1076    fn begin_window_resize(&mut self, edge: crate::csd::CsdHitZone, x: f32, y: f32) {
1077        if let Some(dir) = edge.to_x11_moveresize_direction() {
1078            let _ = self.send_moveresize(x, y, dir, 1);
1079        }
1080    }
1081}
1082
1083impl NativeSurfaceWindow for PureX11Window {
1084    fn present_surface(
1085        &mut self,
1086        pixels: &[u8],
1087        width: u32,
1088        height: u32,
1089    ) -> Result<(), PresentError> {
1090        self.present_bgra(pixels, width, height)
1091    }
1092}
1093
1094#[cfg(feature = "xlib")]
1095/// Inner xlib-backed window managing legacy XOpenDisplay handle when active.
1096pub struct XlibWindowInner {
1097    pub display: *mut xlib::Display,
1098    pub window: xlib::Window,
1099    pub gc: xlib::GC,
1100    pub wm_delete_window: xlib::Atom,
1101    pub config: WindowConfig,
1102    pub scale_factor: f32,
1103    pub is_focused: bool,
1104    pub cursor: CursorIcon,
1105    pub redraw_requested: bool,
1106    pub event_queue: VecDeque<PlatformEvent>,
1107    pub last_click: Option<(std::time::Instant, f32, f32)>,
1108}
1109
1110#[cfg(feature = "xlib")]
1111impl XlibWindowInner {
1112    pub fn new(config: WindowConfig) -> Result<Self, String> {
1113        unsafe {
1114            let display = xlib::XOpenDisplay(std::ptr::null());
1115            if display.is_null() {
1116                return Err("Failed to open X11 display via xlib".to_string());
1117            }
1118
1119            let screen = xlib::XDefaultScreen(display);
1120            let root = xlib::XRootWindow(display, screen);
1121            let black_pixel = xlib::XBlackPixel(display, screen);
1122
1123            let width = config.width.max(100);
1124            let height = config.height.max(100);
1125
1126            let window = xlib::XCreateSimpleWindow(
1127                display,
1128                root,
1129                80,
1130                80,
1131                width,
1132                height,
1133                0,
1134                black_pixel,
1135                black_pixel,
1136            );
1137
1138            if window == 0 {
1139                xlib::XCloseDisplay(display);
1140                return Err("Failed to create X11 window via xlib".to_string());
1141            }
1142
1143            let c_title = CString::new(config.title.as_str())
1144                .unwrap_or_else(|_| CString::new("Strata Application").unwrap());
1145            xlib::XStoreName(display, window, c_title.as_ptr());
1146
1147            let wm_delete_str = CString::new("WM_DELETE_WINDOW").unwrap();
1148            let wm_delete_window = xlib::XInternAtom(display, wm_delete_str.as_ptr(), 0);
1149            let mut protocols = [wm_delete_window];
1150            xlib::XSetWMProtocols(display, window, protocols.as_mut_ptr(), 1);
1151
1152            let event_mask = xlib::ExposureMask
1153                | xlib::KeyPressMask
1154                | xlib::KeyReleaseMask
1155                | xlib::ButtonPressMask
1156                | xlib::ButtonReleaseMask
1157                | xlib::PointerMotionMask
1158                | xlib::StructureNotifyMask
1159                | xlib::FocusChangeMask;
1160            xlib::XSelectInput(display, window, event_mask);
1161
1162            let gc = xlib::XCreateGC(display, window, 0, std::ptr::null_mut());
1163            xlib::XMapWindow(display, window);
1164            xlib::XFlush(display);
1165
1166            Ok(Self {
1167                display,
1168                window,
1169                gc,
1170                wm_delete_window,
1171                config,
1172                scale_factor: 1.0,
1173                is_focused: true,
1174                cursor: CursorIcon::Default,
1175                redraw_requested: true,
1176                event_queue: VecDeque::new(),
1177                last_click: None,
1178            })
1179        }
1180    }
1181
1182    pub fn present_bgra(
1183        &mut self,
1184        buffer: &[u8],
1185        width: u32,
1186        height: u32,
1187    ) -> Result<(), PresentError> {
1188        if self.display.is_null() || self.window == 0 {
1189            return Err(PresentError::SurfaceLost);
1190        }
1191
1192        unsafe {
1193            let screen = xlib::XDefaultScreen(self.display);
1194            let visual = xlib::XDefaultVisual(self.display, screen);
1195            let depth = xlib::XDefaultDepth(self.display, screen);
1196            let data_ptr = buffer.as_ptr() as *mut c_char;
1197
1198            let image = xlib::XCreateImage(
1199                self.display,
1200                visual,
1201                depth as u32,
1202                xlib::ZPixmap,
1203                0,
1204                data_ptr,
1205                width,
1206                height,
1207                32,
1208                (width * 4) as i32,
1209            );
1210
1211            if image.is_null() {
1212                return Err(PresentError::Custom("XCreateImage failed".to_string()));
1213            }
1214
1215            xlib::XPutImage(
1216                self.display,
1217                self.window,
1218                self.gc,
1219                image,
1220                0,
1221                0,
1222                0,
1223                0,
1224                width,
1225                height,
1226            );
1227
1228            xlib::XFlush(self.display);
1229            (*image).data = std::ptr::null_mut();
1230            xlib::XDestroyImage(image);
1231        }
1232
1233        self.redraw_requested = false;
1234        Ok(())
1235    }
1236
1237    pub fn poll_native_events(&mut self) -> Vec<PlatformEvent> {
1238        let mut events = Vec::new();
1239        if self.display.is_null() {
1240            return events;
1241        }
1242
1243        unsafe {
1244            while xlib::XPending(self.display) > 0 {
1245                let mut xevent: xlib::XEvent = std::mem::zeroed();
1246                xlib::XNextEvent(self.display, &mut xevent);
1247
1248                match xevent.get_type() {
1249                    xlib::Expose => {
1250                        self.redraw_requested = true;
1251                    }
1252                    xlib::ConfigureNotify => {
1253                        let conf = xevent.configure;
1254                        let w = conf.width as u32;
1255                        let h = conf.height as u32;
1256                        if w != self.config.width || h != self.config.height {
1257                            self.config.width = w;
1258                            self.config.height = h;
1259                            self.redraw_requested = true;
1260                            events.push(PlatformEvent::WindowResized {
1261                                width: w,
1262                                height: h,
1263                            });
1264                        }
1265                    }
1266                    xlib::ButtonPress => {
1267                        let bp = xevent.button;
1268                        let x = bp.x as f32;
1269                        let y = bp.y as f32;
1270                        match bp.button {
1271                            1 => {
1272                                let now = std::time::Instant::now();
1273                                if let Some((prev_time, px, py)) = self.last_click {
1274                                    if now.duration_since(prev_time).as_millis() < 400
1275                                        && (px - x).abs() < 6.0
1276                                        && (py - y).abs() < 6.0
1277                                    {
1278                                        events.push(PlatformEvent::DoubleClick {
1279                                            button: MouseButton::Left,
1280                                            x,
1281                                            y,
1282                                        });
1283                                        self.last_click = None;
1284                                    } else {
1285                                        self.last_click = Some((now, x, y));
1286                                    }
1287                                } else {
1288                                    self.last_click = Some((now, x, y));
1289                                }
1290                                events.push(PlatformEvent::MouseDown {
1291                                    button: MouseButton::Left,
1292                                    x,
1293                                    y,
1294                                });
1295                            }
1296                            2 => events.push(PlatformEvent::MouseDown {
1297                                button: MouseButton::Middle,
1298                                x,
1299                                y,
1300                            }),
1301                            3 => events.push(PlatformEvent::MouseDown {
1302                                button: MouseButton::Right,
1303                                x,
1304                                y,
1305                            }),
1306                            4 => events.push(PlatformEvent::Scroll {
1307                                delta_x: 0.0,
1308                                delta_y: -1.0,
1309                                is_momentum: false,
1310                            }),
1311                            5 => events.push(PlatformEvent::Scroll {
1312                                delta_x: 0.0,
1313                                delta_y: 1.0,
1314                                is_momentum: false,
1315                            }),
1316                            6 => events.push(PlatformEvent::Scroll {
1317                                delta_x: -1.0,
1318                                delta_y: 0.0,
1319                                is_momentum: false,
1320                            }),
1321                            7 => events.push(PlatformEvent::Scroll {
1322                                delta_x: 1.0,
1323                                delta_y: 0.0,
1324                                is_momentum: false,
1325                            }),
1326                            b => events.push(PlatformEvent::MouseDown {
1327                                button: MouseButton::Other(b as u16),
1328                                x,
1329                                y,
1330                            }),
1331                        }
1332                    }
1333                    xlib::ButtonRelease => {
1334                        let bp = xevent.button;
1335                        let x = bp.x as f32;
1336                        let y = bp.y as f32;
1337                        let button = match bp.button {
1338                            1 => MouseButton::Left,
1339                            2 => MouseButton::Middle,
1340                            3 => MouseButton::Right,
1341                            b => MouseButton::Other(b as u16),
1342                        };
1343                        events.push(PlatformEvent::MouseUp { button, x, y });
1344                    }
1345                    xlib::MotionNotify => {
1346                        let mn = xevent.motion;
1347                        events.push(PlatformEvent::MouseMove {
1348                            x: mn.x as f32,
1349                            y: mn.y as f32,
1350                        });
1351                    }
1352                    xlib::KeyPress => {
1353                        let mut kp = xevent.key;
1354                        let mut buf = [0u8; 32];
1355                        let mut keysym: xlib::KeySym = 0;
1356                        let count = xlib::XLookupString(
1357                            &mut kp,
1358                            buf.as_mut_ptr() as *mut c_char,
1359                            buf.len() as c_int,
1360                            &mut keysym,
1361                            std::ptr::null_mut(),
1362                        );
1363                        let code = map_x11_keysym(keysym);
1364                        events.push(PlatformEvent::KeyDown {
1365                            key: code,
1366                            modifiers: Modifiers::default(),
1367                        });
1368                        if count > 0 {
1369                            if let Ok(s) = std::str::from_utf8(&buf[..count as usize]) {
1370                                for ch in s.chars() {
1371                                    events.push(PlatformEvent::ReceivedCharacter(ch));
1372                                }
1373                            }
1374                        }
1375                    }
1376                    xlib::KeyRelease => {
1377                        let mut kp = xevent.key;
1378                        let mut buf = [0u8; 32];
1379                        let mut keysym: xlib::KeySym = 0;
1380                        let _ = xlib::XLookupString(
1381                            &mut kp,
1382                            buf.as_mut_ptr() as *mut c_char,
1383                            buf.len() as c_int,
1384                            &mut keysym,
1385                            std::ptr::null_mut(),
1386                        );
1387                        let code = map_x11_keysym(keysym);
1388                        events.push(PlatformEvent::KeyUp {
1389                            key: code,
1390                            modifiers: Modifiers::default(),
1391                        });
1392                    }
1393                    xlib::FocusIn => {
1394                        self.is_focused = true;
1395                        events.push(PlatformEvent::WindowFocused(true));
1396                    }
1397                    xlib::FocusOut => {
1398                        self.is_focused = false;
1399                        events.push(PlatformEvent::WindowFocused(false));
1400                    }
1401                    xlib::ClientMessage => {
1402                        let cm = xevent.client_message;
1403                        if cm.data.get_long(0) as c_ulong == self.wm_delete_window {
1404                            events.push(PlatformEvent::WindowCloseRequested);
1405                        }
1406                    }
1407                    _ => {}
1408                }
1409            }
1410        }
1411        events
1412    }
1413}
1414
1415#[cfg(feature = "xlib")]
1416impl Drop for XlibWindowInner {
1417    fn drop(&mut self) {
1418        unsafe {
1419            if !self.display.is_null() {
1420                if !self.gc.is_null() {
1421                    xlib::XFreeGC(self.display, self.gc);
1422                }
1423                if self.window != 0 {
1424                    xlib::XDestroyWindow(self.display, self.window);
1425                }
1426                xlib::XCloseDisplay(self.display);
1427            }
1428        }
1429    }
1430}
1431
1432/// Unified Linux X11 desktop window instance.
1433/// Transparently uses `PureX11Window` by default, falling back to legacy `xlib` if requested and available.
1434pub enum X11Window {
1435    Pure(PureX11Window),
1436    #[cfg(feature = "xlib")]
1437    Xlib(XlibWindowInner),
1438}
1439
1440impl X11Window {
1441    /// Instantiates an X11 window according to the provided configuration.
1442    pub fn new(config: WindowConfig) -> Result<Self, String> {
1443        // 1. Try pure-Rust X11 client first
1444        match PureX11Window::new(config.clone()) {
1445            Ok(pure) => Ok(Self::Pure(pure)),
1446            Err(pure_err) => {
1447                #[cfg(feature = "xlib")]
1448                {
1449                    match XlibWindowInner::new(config) {
1450                        Ok(xlib_win) => Ok(Self::Xlib(xlib_win)),
1451                        Err(xlib_err) => Err(format!(
1452                            "X11 pure client error: {}; xlib fallback error: {}",
1453                            pure_err, xlib_err
1454                        )),
1455                    }
1456                }
1457                #[cfg(not(feature = "xlib"))]
1458                {
1459                    Err(format!("Pure X11 client error: {}", pure_err))
1460                }
1461            }
1462        }
1463    }
1464
1465    /// Returns true if the window is driven by pure-Rust wire protocols without C xlib.
1466    pub fn is_pure(&self) -> bool {
1467        matches!(self, Self::Pure(_))
1468    }
1469
1470    /// Presents a BGRA8 pixel slice directly to the X11 surface.
1471    pub fn present_bgra(
1472        &mut self,
1473        buffer: &[u8],
1474        width: u32,
1475        height: u32,
1476    ) -> Result<(), PresentError> {
1477        match self {
1478            Self::Pure(w) => w.present_bgra(buffer, width, height),
1479            #[cfg(feature = "xlib")]
1480            Self::Xlib(w) => w.present_bgra(buffer, width, height),
1481        }
1482    }
1483
1484    /// Polls pending platform events without blocking.
1485    pub fn poll_native_events(&mut self) -> Vec<PlatformEvent> {
1486        match self {
1487            Self::Pure(w) => w.poll_native_events(),
1488            #[cfg(feature = "xlib")]
1489            Self::Xlib(w) => {
1490                let mut events = w.poll_native_events();
1491                while let Some(ev) = w.event_queue.pop_front() {
1492                    events.push(ev);
1493                }
1494                events
1495            }
1496        }
1497    }
1498}
1499
1500impl PlatformWindow for X11Window {
1501    fn title(&self) -> &str {
1502        match self {
1503            Self::Pure(w) => w.title(),
1504            #[cfg(feature = "xlib")]
1505            Self::Xlib(w) => &w.config.title,
1506        }
1507    }
1508
1509    fn set_title(&mut self, title: &str) {
1510        match self {
1511            Self::Pure(w) => w.set_title(title),
1512            #[cfg(feature = "xlib")]
1513            Self::Xlib(w) => {
1514                w.config.title = title.to_string();
1515                if !w.display.is_null() && w.window != 0 {
1516                    if let Ok(c_title) = CString::new(title) {
1517                        unsafe {
1518                            xlib::XStoreName(w.display, w.window, c_title.as_ptr());
1519                            xlib::XFlush(w.display);
1520                        }
1521                    }
1522                }
1523            }
1524        }
1525    }
1526
1527    fn size(&self) -> (u32, u32) {
1528        match self {
1529            Self::Pure(w) => w.size(),
1530            #[cfg(feature = "xlib")]
1531            Self::Xlib(w) => (w.config.width, w.config.height),
1532        }
1533    }
1534
1535    fn set_size(&mut self, width: u32, height: u32) {
1536        match self {
1537            Self::Pure(w) => w.set_size(width, height),
1538            #[cfg(feature = "xlib")]
1539            Self::Xlib(w) => {
1540                w.config.width = width;
1541                w.config.height = height;
1542                if !w.display.is_null() && w.window != 0 {
1543                    unsafe {
1544                        xlib::XResizeWindow(w.display, w.window, width, height);
1545                        xlib::XFlush(w.display);
1546                    }
1547                }
1548                w.redraw_requested = true;
1549            }
1550        }
1551    }
1552
1553    fn scale_factor(&self) -> f32 {
1554        match self {
1555            Self::Pure(w) => w.scale_factor(),
1556            #[cfg(feature = "xlib")]
1557            Self::Xlib(w) => w.scale_factor,
1558        }
1559    }
1560
1561    fn set_scale_factor(&mut self, scale_factor: f32) {
1562        match self {
1563            Self::Pure(w) => w.set_scale_factor(scale_factor),
1564            #[cfg(feature = "xlib")]
1565            Self::Xlib(w) => {
1566                w.scale_factor = scale_factor;
1567                w.redraw_requested = true;
1568            }
1569        }
1570    }
1571
1572    fn mode(&self) -> WindowMode {
1573        match self {
1574            Self::Pure(w) => w.mode(),
1575            #[cfg(feature = "xlib")]
1576            Self::Xlib(w) => w.config.mode,
1577        }
1578    }
1579
1580    fn set_mode(&mut self, mode: WindowMode) {
1581        match self {
1582            Self::Pure(w) => w.set_mode(mode),
1583            #[cfg(feature = "xlib")]
1584            Self::Xlib(w) => {
1585                let prev = w.config.mode;
1586                w.config.mode = mode;
1587                w.redraw_requested = true;
1588                if mode == WindowMode::Maximized && prev != WindowMode::Maximized {
1589                    w.event_queue
1590                        .push_back(PlatformEvent::WindowMaximized(true));
1591                } else if mode != WindowMode::Maximized && prev == WindowMode::Maximized {
1592                    w.event_queue
1593                        .push_back(PlatformEvent::WindowMaximized(false));
1594                }
1595            }
1596        }
1597    }
1598
1599    fn is_focused(&self) -> bool {
1600        match self {
1601            Self::Pure(w) => w.is_focused(),
1602            #[cfg(feature = "xlib")]
1603            Self::Xlib(w) => w.is_focused,
1604        }
1605    }
1606
1607    fn set_focused(&mut self, focused: bool) {
1608        match self {
1609            Self::Pure(w) => w.set_focused(focused),
1610            #[cfg(feature = "xlib")]
1611            Self::Xlib(w) => w.is_focused = focused,
1612        }
1613    }
1614
1615    fn cursor(&self) -> CursorIcon {
1616        match self {
1617            Self::Pure(w) => w.cursor(),
1618            #[cfg(feature = "xlib")]
1619            Self::Xlib(w) => w.cursor,
1620        }
1621    }
1622
1623    fn set_cursor(&mut self, cursor: CursorIcon) {
1624        match self {
1625            Self::Pure(w) => w.set_cursor(cursor),
1626            #[cfg(feature = "xlib")]
1627            Self::Xlib(w) => w.cursor = cursor,
1628        }
1629    }
1630
1631    fn request_redraw(&mut self) {
1632        match self {
1633            Self::Pure(w) => w.request_redraw(),
1634            #[cfg(feature = "xlib")]
1635            Self::Xlib(w) => w.redraw_requested = true,
1636        }
1637    }
1638
1639    fn is_redraw_requested(&self) -> bool {
1640        match self {
1641            Self::Pure(w) => w.is_redraw_requested(),
1642            #[cfg(feature = "xlib")]
1643            Self::Xlib(w) => w.redraw_requested,
1644        }
1645    }
1646
1647    fn poll_events(&mut self) -> Vec<PlatformEvent> {
1648        self.poll_native_events()
1649    }
1650
1651    fn push_event(&mut self, event: PlatformEvent) {
1652        match self {
1653            Self::Pure(w) => w.push_event(event),
1654            #[cfg(feature = "xlib")]
1655            Self::Xlib(w) => w.event_queue.push_back(event),
1656        }
1657    }
1658
1659    fn begin_window_drag(&mut self, x: f32, y: f32) {
1660        match self {
1661            Self::Pure(w) => w.begin_window_drag(x, y),
1662            #[cfg(feature = "xlib")]
1663            Self::Xlib(_) => {}
1664        }
1665    }
1666
1667    fn begin_window_resize(&mut self, edge: crate::csd::CsdHitZone, x: f32, y: f32) {
1668        match self {
1669            Self::Pure(w) => w.begin_window_resize(edge, x, y),
1670            #[cfg(feature = "xlib")]
1671            Self::Xlib(_) => {}
1672        }
1673    }
1674}
1675
1676impl NativeSurfaceWindow for X11Window {
1677    fn present_surface(
1678        &mut self,
1679        pixels: &[u8],
1680        width: u32,
1681        height: u32,
1682    ) -> Result<(), PresentError> {
1683        self.present_bgra(pixels, width, height)
1684    }
1685}
1686
1687/// Linux X11 Event Loop driving message dispatch and frame pacing.
1688pub struct X11EventLoop {
1689    pub window: X11Window,
1690}
1691
1692impl X11EventLoop {
1693    pub fn new(window: X11Window) -> Self {
1694        Self { window }
1695    }
1696}
1697
1698impl EventLoop for X11EventLoop {
1699    fn run<F>(&mut self, mut handler: F)
1700    where
1701        F: FnMut(PlatformEvent, &mut EventLoopControl),
1702    {
1703        let mut control = EventLoopControl::Poll;
1704
1705        while control != EventLoopControl::Exit {
1706            let events = self.window.poll_events();
1707            for event in events {
1708                handler(event, &mut control);
1709                if control == EventLoopControl::Exit {
1710                    return;
1711                }
1712            }
1713
1714            match control {
1715                EventLoopControl::Poll => std::thread::yield_now(),
1716                EventLoopControl::Wait => std::thread::sleep(Duration::from_millis(150)),
1717                EventLoopControl::WaitUntil(instant) => {
1718                    let now = std::time::Instant::now();
1719                    if let Some(dur) = instant.checked_duration_since(now) {
1720                        std::thread::sleep(dur.min(Duration::from_millis(150)));
1721                    }
1722                }
1723                EventLoopControl::Exit => break,
1724            }
1725        }
1726    }
1727}
1728
1729/// Translates Linux evdev hardware keycodes from pure-Rust X11 events into Strata `KeyCode` and characters.
1730pub fn map_x11_pure_keycode(keycode: u8) -> (KeyCode, Option<char>) {
1731    let evdev = keycode.saturating_sub(8);
1732    match evdev {
1733        1 => (KeyCode::Escape, None),
1734        2 => (KeyCode::Digit1, Some('1')),
1735        3 => (KeyCode::Digit2, Some('2')),
1736        4 => (KeyCode::Digit3, Some('3')),
1737        5 => (KeyCode::Digit4, Some('4')),
1738        6 => (KeyCode::Digit5, Some('5')),
1739        7 => (KeyCode::Digit6, Some('6')),
1740        8 => (KeyCode::Digit7, Some('7')),
1741        9 => (KeyCode::Digit8, Some('8')),
1742        10 => (KeyCode::Digit9, Some('9')),
1743        11 => (KeyCode::Digit0, Some('0')),
1744        12 => (KeyCode::Minus, Some('-')),
1745        13 => (KeyCode::Equals, Some('=')),
1746        14 => (KeyCode::Backspace, None),
1747        15 => (KeyCode::Tab, Some('\t')),
1748        16 => (KeyCode::KeyQ, Some('q')),
1749        17 => (KeyCode::KeyW, Some('w')),
1750        18 => (KeyCode::KeyE, Some('e')),
1751        19 => (KeyCode::KeyR, Some('r')),
1752        20 => (KeyCode::KeyT, Some('t')),
1753        21 => (KeyCode::KeyY, Some('y')),
1754        22 => (KeyCode::KeyU, Some('u')),
1755        23 => (KeyCode::KeyI, Some('i')),
1756        24 => (KeyCode::KeyO, Some('o')),
1757        25 => (KeyCode::KeyP, Some('p')),
1758        26 => (KeyCode::BracketLeft, Some('[')),
1759        27 => (KeyCode::BracketRight, Some(']')),
1760        28 => (KeyCode::Enter, Some('\n')),
1761        30 => (KeyCode::KeyA, Some('a')),
1762        31 => (KeyCode::KeyS, Some('s')),
1763        32 => (KeyCode::KeyD, Some('d')),
1764        33 => (KeyCode::KeyF, Some('f')),
1765        34 => (KeyCode::KeyG, Some('g')),
1766        35 => (KeyCode::KeyH, Some('h')),
1767        36 => (KeyCode::KeyJ, Some('j')),
1768        37 => (KeyCode::KeyK, Some('k')),
1769        38 => (KeyCode::KeyL, Some('l')),
1770        39 => (KeyCode::Semicolon, Some(';')),
1771        40 => (KeyCode::Quote, Some('\'')),
1772        41 => (KeyCode::Backquote, Some('`')),
1773        43 => (KeyCode::Backslash, Some('\\')),
1774        44 => (KeyCode::KeyZ, Some('z')),
1775        45 => (KeyCode::KeyX, Some('x')),
1776        46 => (KeyCode::KeyC, Some('c')),
1777        47 => (KeyCode::KeyV, Some('v')),
1778        48 => (KeyCode::KeyB, Some('b')),
1779        49 => (KeyCode::KeyN, Some('n')),
1780        50 => (KeyCode::KeyM, Some('m')),
1781        51 => (KeyCode::Comma, Some(',')),
1782        52 => (KeyCode::Period, Some('.')),
1783        53 => (KeyCode::Slash, Some('/')),
1784        57 => (KeyCode::Space, Some(' ')),
1785        103 => (KeyCode::ArrowUp, None),
1786        105 => (KeyCode::ArrowLeft, None),
1787        106 => (KeyCode::ArrowRight, None),
1788        108 => (KeyCode::ArrowDown, None),
1789        111 => (KeyCode::Delete, None),
1790        _ => (KeyCode::Unknown, None),
1791    }
1792}
1793
1794#[cfg(feature = "xlib")]
1795pub fn map_x11_keysym(keysym: xlib::KeySym) -> KeyCode {
1796    match keysym {
1797        0xFF08 => KeyCode::Backspace,
1798        0xFF09 => KeyCode::Tab,
1799        0xFF0D => KeyCode::Enter,
1800        0xFF1B => KeyCode::Escape,
1801        0xFF51 => KeyCode::ArrowLeft,
1802        0xFF52 => KeyCode::ArrowUp,
1803        0xFF53 => KeyCode::ArrowRight,
1804        0xFF54 => KeyCode::ArrowDown,
1805        0xFFFF => KeyCode::Delete,
1806        0x0020 => KeyCode::Space,
1807        0x002F | 0x003F => KeyCode::Slash,
1808        0x002C | 0x003C => KeyCode::Comma,
1809        0x002E | 0x003E => KeyCode::Period,
1810        0x002D | 0x005F => KeyCode::Minus,
1811        0x003D | 0x002B => KeyCode::Equals,
1812        0x005B | 0x007B => KeyCode::BracketLeft,
1813        0x005D | 0x007D => KeyCode::BracketRight,
1814        0x003B | 0x003A => KeyCode::Semicolon,
1815        0x0027 | 0x0022 => KeyCode::Quote,
1816        0x005C | 0x007C => KeyCode::Backslash,
1817        0x0060 | 0x007E => KeyCode::Backquote,
1818        0x0030..=0x0039 => match keysym - 0x0030 {
1819            0 => KeyCode::Digit0,
1820            1 => KeyCode::Digit1,
1821            2 => KeyCode::Digit2,
1822            3 => KeyCode::Digit3,
1823            4 => KeyCode::Digit4,
1824            5 => KeyCode::Digit5,
1825            6 => KeyCode::Digit6,
1826            7 => KeyCode::Digit7,
1827            8 => KeyCode::Digit8,
1828            _ => KeyCode::Digit9,
1829        },
1830        0x0041..=0x005A | 0x0061..=0x007A => {
1831            let c = if keysym >= 0x0061 {
1832                keysym - 0x0061
1833            } else {
1834                keysym - 0x0041
1835            };
1836            match c {
1837                0 => KeyCode::KeyA,
1838                1 => KeyCode::KeyB,
1839                2 => KeyCode::KeyC,
1840                3 => KeyCode::KeyD,
1841                4 => KeyCode::KeyE,
1842                5 => KeyCode::KeyF,
1843                6 => KeyCode::KeyG,
1844                7 => KeyCode::KeyH,
1845                8 => KeyCode::KeyI,
1846                9 => KeyCode::KeyJ,
1847                10 => KeyCode::KeyK,
1848                11 => KeyCode::KeyL,
1849                12 => KeyCode::KeyM,
1850                13 => KeyCode::KeyN,
1851                14 => KeyCode::KeyO,
1852                15 => KeyCode::KeyP,
1853                16 => KeyCode::KeyQ,
1854                17 => KeyCode::KeyR,
1855                18 => KeyCode::KeyS,
1856                19 => KeyCode::KeyT,
1857                20 => KeyCode::KeyU,
1858                21 => KeyCode::KeyV,
1859                22 => KeyCode::KeyW,
1860                23 => KeyCode::KeyX,
1861                24 => KeyCode::KeyY,
1862                _ => KeyCode::KeyZ,
1863            }
1864        }
1865        _ => KeyCode::Unknown,
1866    }
1867}