Skip to main content

strata_platform/
wayland_window.rs

1//! Pure-Rust Wayland Client Protocol Backend and Hardware Event Loop.
2//!
3//! Provides zero-dependency native Wayland windowing over UNIX domain sockets
4//! (`$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY` or `wayland-0`), wire protocol encoding/decoding,
5//! POSIX shared memory surface presentation (`wl_shm`), XDG Shell window lifecycle
6//! (`xdg_wm_base`, `xdg_surface`, `xdg_toplevel`), and input event translation (`wl_seat`).
7
8#![cfg(target_os = "linux")]
9
10use crate::events::{KeyCode, Modifiers, MouseButton, PlatformEvent};
11use crate::raw_abi::wayland::WaylandHeader;
12use crate::window::{
13    CursorIcon, EventLoop, EventLoopControl, PlatformWindow, WindowConfig, WindowMode,
14};
15use std::collections::VecDeque;
16use std::io::Read;
17use std::os::unix::io::{AsRawFd, RawFd};
18use std::os::unix::net::UnixStream;
19
20// Standard Wayland wire format constants
21pub const WL_DISPLAY_ID: u32 = 1;
22
23// wl_display opcodes
24pub const WL_DISPLAY_SYNC: u16 = 0;
25pub const WL_DISPLAY_GET_REGISTRY: u16 = 1;
26
27// wl_registry opcodes
28pub const WL_REGISTRY_BIND: u16 = 0;
29
30// wl_compositor opcodes
31pub const WL_COMPOSITOR_CREATE_SURFACE: u16 = 0;
32
33// wl_shm opcodes & formats
34pub const WL_SHM_CREATE_POOL: u16 = 0;
35pub const WL_SHM_FORMAT_ARGB8888: u32 = 0;
36pub const WL_SHM_FORMAT_XRGB8888: u32 = 1;
37
38// wl_shm_pool opcodes
39pub const WL_SHM_POOL_CREATE_BUFFER: u16 = 0;
40pub const WL_SHM_POOL_DESTROY: u16 = 1;
41pub const WL_SHM_POOL_RESIZE: u16 = 2;
42
43// wl_surface opcodes
44pub const WL_SURFACE_DESTROY: u16 = 0;
45pub const WL_SURFACE_ATTACH: u16 = 1;
46pub const WL_SURFACE_DAMAGE: u16 = 2;
47pub const WL_SURFACE_COMMIT: u16 = 6;
48
49// xdg_wm_base opcodes
50pub const XDG_WM_BASE_DESTROY: u16 = 0;
51pub const XDG_WM_BASE_GET_XDG_SURFACE: u16 = 2;
52pub const XDG_WM_BASE_PONG: u16 = 3;
53
54// xdg_surface opcodes
55pub const XDG_SURFACE_DESTROY: u16 = 0;
56pub const XDG_SURFACE_GET_TOPLEVEL: u16 = 1;
57pub const XDG_SURFACE_ACK_CONFIGURE: u16 = 4;
58
59// xdg_toplevel opcodes
60pub const XDG_TOPLEVEL_DESTROY: u16 = 0;
61pub const XDG_TOPLEVEL_SET_TITLE: u16 = 2;
62pub const XDG_TOPLEVEL_SET_APP_ID: u16 = 3;
63pub const XDG_TOPLEVEL_MOVE: u16 = 5;
64pub const XDG_TOPLEVEL_RESIZE: u16 = 6;
65pub const XDG_TOPLEVEL_SET_MAXIMIZED: u16 = 9;
66pub const XDG_TOPLEVEL_UNSET_MAXIMIZED: u16 = 10;
67pub const XDG_TOPLEVEL_SET_MINIMIZED: u16 = 13;
68
69// wl_seat opcodes
70pub const WL_SEAT_GET_POINTER: u16 = 0;
71pub const WL_SEAT_GET_KEYBOARD: u16 = 1;
72
73/// Low-level Wayland wire protocol message encoder.
74#[derive(Debug, Default)]
75pub struct WaylandEncoder {
76    buffer: Vec<u8>,
77}
78
79impl WaylandEncoder {
80    /// Creates a new empty message encoder.
81    pub fn new() -> Self {
82        Self {
83            buffer: Vec::with_capacity(128),
84        }
85    }
86
87    /// Clears the encoder buffer.
88    pub fn clear(&mut self) {
89        self.buffer.clear();
90    }
91
92    /// Returns the encoded message slice.
93    pub fn as_bytes(&self) -> &[u8] {
94        &self.buffer
95    }
96
97    /// Reserves space for the 8-byte Wayland header.
98    pub fn begin_message(&mut self) {
99        self.buffer.clear();
100        self.buffer.extend_from_slice(&[0u8; 8]);
101    }
102
103    /// Finalizes the header with the target object ID and opcode.
104    pub fn finish_message(&mut self, object_id: u32, opcode: u16) {
105        let size = self.buffer.len() as u16;
106        let header = WaylandHeader {
107            object_id,
108            opcode,
109            size,
110        };
111        self.buffer[0..8].copy_from_slice(&header.to_bytes());
112    }
113
114    /// Appends a 32-bit unsigned integer.
115    pub fn push_u32(&mut self, val: u32) {
116        self.buffer.extend_from_slice(&val.to_ne_bytes());
117    }
118
119    /// Appends a 32-bit signed integer.
120    pub fn push_i32(&mut self, val: i32) {
121        self.buffer.extend_from_slice(&val.to_ne_bytes());
122    }
123
124    /// Appends a 24.8 signed fixed-point value.
125    pub fn push_fixed(&mut self, val: f64) {
126        let fixed = (val * 256.0) as i32;
127        self.push_i32(fixed);
128    }
129
130    /// Appends a length-prefixed, null-terminated, 4-byte aligned string.
131    pub fn push_string(&mut self, s: &str) {
132        let bytes = s.as_bytes();
133        let len = (bytes.len() + 1) as u32; // including trailing null
134        self.push_u32(len);
135        self.buffer.extend_from_slice(bytes);
136        self.buffer.push(0); // trailing null
137                             // Align to 4 bytes
138        while !self.buffer.len().is_multiple_of(4) {
139            self.buffer.push(0);
140        }
141    }
142}
143
144/// Low-level Wayland wire protocol message decoder.
145#[derive(Debug)]
146pub struct WaylandDecoder<'a> {
147    data: &'a [u8],
148    offset: usize,
149}
150
151impl<'a> WaylandDecoder<'a> {
152    /// Creates a decoder for the specified message payload (after the 8-byte header).
153    pub fn new(data: &'a [u8]) -> Self {
154        Self { data, offset: 0 }
155    }
156
157    /// Remaining undecoded bytes.
158    pub fn remaining(&self) -> usize {
159        self.data.len().saturating_sub(self.offset)
160    }
161
162    /// Reads a 32-bit unsigned integer.
163    pub fn read_u32(&mut self) -> Option<u32> {
164        if self.remaining() < 4 {
165            return None;
166        }
167        let val = u32::from_ne_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
168        self.offset += 4;
169        Some(val)
170    }
171
172    /// Reads a 32-bit signed integer.
173    pub fn read_i32(&mut self) -> Option<i32> {
174        if self.remaining() < 4 {
175            return None;
176        }
177        let val = i32::from_ne_bytes(self.data[self.offset..self.offset + 4].try_into().unwrap());
178        self.offset += 4;
179        Some(val)
180    }
181
182    /// Reads a 24.8 signed fixed-point number as f64.
183    pub fn read_fixed(&mut self) -> Option<f64> {
184        self.read_i32().map(|fixed| fixed as f64 / 256.0)
185    }
186
187    /// Reads a length-prefixed, 4-byte aligned string.
188    pub fn read_string(&mut self) -> Option<String> {
189        let len = self.read_u32()? as usize;
190        if len == 0 || self.remaining() < len {
191            return None;
192        }
193        let raw_str = &self.data[self.offset..self.offset + len];
194        let aligned_len = (len + 3) & !3;
195        self.offset += aligned_len.min(self.remaining());
196
197        let trimmed = if let Some(null_pos) = raw_str.iter().position(|&b| b == 0) {
198            &raw_str[..null_pos]
199        } else {
200            raw_str
201        };
202        String::from_utf8(trimmed.to_vec()).ok()
203    }
204}
205
206/// Helper to send bytes with an optional file descriptor via `sendmsg` (`SCM_RIGHTS`).
207fn sendmsg_with_fd(
208    socket_fd: RawFd,
209    data: &[u8],
210    fd_to_send: Option<RawFd>,
211) -> std::io::Result<()> {
212    unsafe {
213        let mut iov = libc::iovec {
214            iov_base: data.as_ptr() as *mut libc::c_void,
215            iov_len: data.len(),
216        };
217
218        let mut msg: libc::msghdr = std::mem::zeroed();
219        msg.msg_iov = &mut iov;
220        msg.msg_iovlen = 1;
221
222        if let Some(fd) = fd_to_send {
223            let cmsg_space = libc::CMSG_SPACE(std::mem::size_of::<RawFd>() as u32) as usize;
224            let mut cmsg_buf = vec![0u8; cmsg_space];
225
226            msg.msg_control = cmsg_buf.as_mut_ptr() as *mut libc::c_void;
227            msg.msg_controllen = cmsg_space;
228
229            let cmsg = libc::CMSG_FIRSTHDR(&msg);
230            (*cmsg).cmsg_level = libc::SOL_SOCKET;
231            (*cmsg).cmsg_type = libc::SCM_RIGHTS;
232            (*cmsg).cmsg_len = libc::CMSG_LEN(std::mem::size_of::<RawFd>() as u32) as usize;
233
234            let fd_ptr = libc::CMSG_DATA(cmsg) as *mut RawFd;
235            std::ptr::write_unaligned(fd_ptr, fd);
236
237            let ret = libc::sendmsg(socket_fd, &msg, 0);
238            if ret < 0 {
239                return Err(std::io::Error::last_os_error());
240            }
241        } else {
242            let ret = libc::sendmsg(socket_fd, &msg, 0);
243            if ret < 0 {
244                return Err(std::io::Error::last_os_error());
245            }
246        }
247    }
248    Ok(())
249}
250
251/// Creates a POSIX shared memory file descriptor of the requested byte size.
252fn create_shm_fd(size: usize) -> std::io::Result<RawFd> {
253    unsafe {
254        let name = std::ffi::CString::new("strata-wayland-shm").unwrap();
255        let mut fd = libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING);
256        if fd < 0 {
257            // Fallback: temp file in XDG_RUNTIME_DIR or /tmp
258            let path = if let Ok(runtime) = std::env::var("XDG_RUNTIME_DIR") {
259                format!("{}/strata-shm-XXXXXX\0", runtime)
260            } else {
261                "/tmp/strata-shm-XXXXXX\0".to_string()
262            };
263            let mut template = path.into_bytes();
264            fd = libc::mkostemp(template.as_mut_ptr() as *mut libc::c_char, libc::O_CLOEXEC);
265            if fd >= 0 {
266                libc::unlink(template.as_ptr() as *const libc::c_char);
267            }
268        }
269        if fd < 0 {
270            return Err(std::io::Error::last_os_error());
271        }
272
273        if libc::ftruncate(fd, size as libc::off_t) < 0 {
274            libc::close(fd);
275            return Err(std::io::Error::last_os_error());
276        }
277
278        Ok(fd)
279    }
280}
281
282/// Shared memory buffer mapping for software surface swapchain presentation.
283pub struct ShmBuffer {
284    pub fd: RawFd,
285    pub pool_id: u32,
286    pub buffer_id: u32,
287    pub width: u32,
288    pub height: u32,
289    pub size: usize,
290    pub ptr: *mut u8,
291}
292
293impl ShmBuffer {
294    /// Allocates and mmaps a new shared memory pixel buffer.
295    pub fn new(pool_id: u32, buffer_id: u32, width: u32, height: u32) -> Result<Self, String> {
296        let size = (width * height * 4) as usize;
297        let fd = create_shm_fd(size).map_err(|e| format!("Failed to create shm fd: {}", e))?;
298
299        let ptr = unsafe {
300            let p = libc::mmap(
301                std::ptr::null_mut(),
302                size,
303                libc::PROT_READ | libc::PROT_WRITE,
304                libc::MAP_SHARED,
305                fd,
306                0,
307            );
308            if p == libc::MAP_FAILED {
309                libc::close(fd);
310                return Err("Failed to mmap shm fd".to_string());
311            }
312            p as *mut u8
313        };
314
315        Ok(Self {
316            fd,
317            pool_id,
318            buffer_id,
319            width,
320            height,
321            size,
322            ptr,
323        })
324    }
325
326    /// Copies BGRA pixels into the mapped shared memory area.
327    pub fn write_pixels(&mut self, pixels: &[u8]) {
328        let copy_len = pixels.len().min(self.size);
329        unsafe {
330            std::ptr::copy_nonoverlapping(pixels.as_ptr(), self.ptr, copy_len);
331        }
332    }
333}
334
335impl Drop for ShmBuffer {
336    fn drop(&mut self) {
337        unsafe {
338            libc::munmap(self.ptr as *mut libc::c_void, self.size);
339            libc::close(self.fd);
340        }
341    }
342}
343
344/// Discovered global Wayland objects in compositor registry.
345#[derive(Debug, Default, Clone)]
346pub struct WaylandGlobals {
347    pub compositor_name: Option<u32>,
348    pub shm_name: Option<u32>,
349    pub xdg_wm_base_name: Option<u32>,
350    pub seat_name: Option<u32>,
351}
352
353/// Pure-Rust Wayland window implementation backed by UNIX domain socket IPC.
354pub struct WaylandWindow {
355    stream: Option<UnixStream>,
356    config: WindowConfig,
357    scale_factor: f32,
358    is_focused: bool,
359    cursor: CursorIcon,
360    pub redraw_requested: bool,
361    event_queue: VecDeque<PlatformEvent>,
362    encoder: WaylandEncoder,
363    next_id: u32,
364    pub globals: WaylandGlobals,
365    // Bound object IDs
366    pub registry_id: u32,
367    pub compositor_id: u32,
368    pub shm_id: u32,
369    pub xdg_wm_base_id: u32,
370    pub seat_id: u32,
371    pub surface_id: u32,
372    pub xdg_surface_id: u32,
373    pub xdg_toplevel_id: u32,
374    pub pointer_id: u32,
375    pub keyboard_id: u32,
376    pub last_serial: u32,
377    // Swapchain Shm Buffer
378    pub shm_buffer: Option<ShmBuffer>,
379    read_buffer: Vec<u8>,
380    pub cursor_pos: (f32, f32),
381    pub last_click: Option<(std::time::Instant, f32, f32)>,
382}
383
384impl WaylandWindow {
385    /// Attempts to connect to the active Wayland compositor and instantiate a native window.
386    pub fn new(config: WindowConfig) -> Result<Self, String> {
387        let socket_path = crate::raw_abi::wayland::default_socket_path();
388        let stream = UnixStream::connect(&socket_path).map_err(|e| {
389            format!(
390                "Cannot connect to Wayland socket \"{}\": {}",
391                socket_path, e
392            )
393        })?;
394        stream
395            .set_nonblocking(true)
396            .map_err(|e| format!("Failed to set nonblocking stream: {}", e))?;
397
398        let mut window = Self {
399            stream: Some(stream),
400            config,
401            scale_factor: 1.0,
402            is_focused: true,
403            cursor: CursorIcon::Default,
404            redraw_requested: true,
405            event_queue: VecDeque::new(),
406            encoder: WaylandEncoder::new(),
407            next_id: 2,
408            globals: WaylandGlobals::default(),
409            registry_id: 2,
410            compositor_id: 3,
411            shm_id: 4,
412            xdg_wm_base_id: 5,
413            seat_id: 6,
414            surface_id: 7,
415            xdg_surface_id: 8,
416            xdg_toplevel_id: 9,
417            pointer_id: 10,
418            keyboard_id: 11,
419            last_serial: 0,
420            shm_buffer: None,
421            read_buffer: Vec::with_capacity(4096),
422            cursor_pos: (0.0, 0.0),
423            last_click: None,
424        };
425
426        window.init_wayland_connection()?;
427        Ok(window)
428    }
429
430    /// Allocates an internal object ID.
431    fn allocate_id(&mut self) -> u32 {
432        let id = self.next_id;
433        self.next_id += 1;
434        id
435    }
436
437    /// Sends encoded message down the UNIX socket.
438    fn send_message(&mut self, fd_to_send: Option<RawFd>) -> Result<(), String> {
439        if let Some(ref mut stream) = self.stream {
440            let bytes = self.encoder.as_bytes();
441            sendmsg_with_fd(stream.as_raw_fd(), bytes, fd_to_send)
442                .map_err(|e| format!("Wayland sendmsg error: {}", e))?;
443            self.encoder.clear();
444            Ok(())
445        } else {
446            Ok(())
447        }
448    }
449
450    /// Performs the initial Wayland connection handshake: binds registry, waits for globals,
451    /// creates surface and toplevel window.
452    fn init_wayland_connection(&mut self) -> Result<(), String> {
453        // 1. Get registry (object 1, opcode 1 -> registry_id 2)
454        self.registry_id = self.allocate_id();
455        self.encoder.begin_message();
456        self.encoder.push_u32(self.registry_id);
457        self.encoder
458            .finish_message(WL_DISPLAY_ID, WL_DISPLAY_GET_REGISTRY);
459        self.send_message(None)?;
460
461        // 2. Sync to receive initial registry globals
462        let sync_cb = self.allocate_id();
463        self.encoder.begin_message();
464        self.encoder.push_u32(sync_cb);
465        self.encoder.finish_message(WL_DISPLAY_ID, WL_DISPLAY_SYNC);
466        self.send_message(None)?;
467
468        // Read until sync callback completes
469        self.roundtrip(sync_cb)?;
470
471        // 3. Bind required global interfaces
472        if let Some(comp_name) = self.globals.compositor_name {
473            self.compositor_id = self.allocate_id();
474            self.encoder.begin_message();
475            self.encoder.push_u32(comp_name);
476            self.encoder.push_string("wl_compositor");
477            self.encoder.push_u32(4); // version 4
478            self.encoder.push_u32(self.compositor_id);
479            self.encoder
480                .finish_message(self.registry_id, WL_REGISTRY_BIND);
481            self.send_message(None)?;
482        } else {
483            return Err("Wayland compositor does not export wl_compositor".to_string());
484        }
485
486        if let Some(shm_name) = self.globals.shm_name {
487            self.shm_id = self.allocate_id();
488            self.encoder.begin_message();
489            self.encoder.push_u32(shm_name);
490            self.encoder.push_string("wl_shm");
491            self.encoder.push_u32(1); // version 1
492            self.encoder.push_u32(self.shm_id);
493            self.encoder
494                .finish_message(self.registry_id, WL_REGISTRY_BIND);
495            self.send_message(None)?;
496        } else {
497            return Err("Wayland compositor does not export wl_shm".to_string());
498        }
499
500        if let Some(wm_name) = self.globals.xdg_wm_base_name {
501            self.xdg_wm_base_id = self.allocate_id();
502            self.encoder.begin_message();
503            self.encoder.push_u32(wm_name);
504            self.encoder.push_string("xdg_wm_base");
505            self.encoder.push_u32(1); // version 1
506            self.encoder.push_u32(self.xdg_wm_base_id);
507            self.encoder
508                .finish_message(self.registry_id, WL_REGISTRY_BIND);
509            self.send_message(None)?;
510        } else {
511            return Err("Wayland compositor does not export xdg_wm_base".to_string());
512        }
513
514        if let Some(seat_name) = self.globals.seat_name {
515            self.seat_id = self.allocate_id();
516            self.encoder.begin_message();
517            self.encoder.push_u32(seat_name);
518            self.encoder.push_string("wl_seat");
519            self.encoder.push_u32(5); // version 5
520            self.encoder.push_u32(self.seat_id);
521            self.encoder
522                .finish_message(self.registry_id, WL_REGISTRY_BIND);
523            self.send_message(None)?;
524
525            // Bind pointer and keyboard
526            self.pointer_id = self.allocate_id();
527            self.encoder.begin_message();
528            self.encoder.push_u32(self.pointer_id);
529            self.encoder
530                .finish_message(self.seat_id, WL_SEAT_GET_POINTER);
531            self.send_message(None)?;
532
533            self.keyboard_id = self.allocate_id();
534            self.encoder.begin_message();
535            self.encoder.push_u32(self.keyboard_id);
536            self.encoder
537                .finish_message(self.seat_id, WL_SEAT_GET_KEYBOARD);
538            self.send_message(None)?;
539        }
540
541        // 4. Create surface
542        self.surface_id = self.allocate_id();
543        self.encoder.begin_message();
544        self.encoder.push_u32(self.surface_id);
545        self.encoder
546            .finish_message(self.compositor_id, WL_COMPOSITOR_CREATE_SURFACE);
547        self.send_message(None)?;
548
549        // 5. Create xdg_surface
550        self.xdg_surface_id = self.allocate_id();
551        self.encoder.begin_message();
552        self.encoder.push_u32(self.xdg_surface_id);
553        self.encoder.push_u32(self.surface_id);
554        self.encoder
555            .finish_message(self.xdg_wm_base_id, XDG_WM_BASE_GET_XDG_SURFACE);
556        self.send_message(None)?;
557
558        // 6. Create xdg_toplevel
559        self.xdg_toplevel_id = self.allocate_id();
560        self.encoder.begin_message();
561        self.encoder.push_u32(self.xdg_toplevel_id);
562        self.encoder
563            .finish_message(self.xdg_surface_id, XDG_SURFACE_GET_TOPLEVEL);
564        self.send_message(None)?;
565
566        // Set title and app_id
567        self.encoder.begin_message();
568        self.encoder.push_string(&self.config.title);
569        self.encoder
570            .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_TITLE);
571        self.send_message(None)?;
572
573        self.encoder.begin_message();
574        self.encoder.push_string("strata");
575        self.encoder
576            .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_APP_ID);
577        self.send_message(None)?;
578
579        // Initial commit to request configure event
580        self.encoder.begin_message();
581        self.encoder
582            .finish_message(self.surface_id, WL_SURFACE_COMMIT);
583        self.send_message(None)?;
584
585        // Allocate initial SHM buffer
586        self.recreate_shm_buffer(self.config.width, self.config.height)?;
587
588        Ok(())
589    }
590
591    /// Re-allocates the shared memory buffer and registers it with the compositor.
592    fn recreate_shm_buffer(&mut self, width: u32, height: u32) -> Result<(), String> {
593        let pool_id = self.allocate_id();
594        let buffer_id = self.allocate_id();
595        let buffer = ShmBuffer::new(pool_id, buffer_id, width, height)?;
596
597        // Send wl_shm.create_pool with buffer fd
598        self.encoder.begin_message();
599        self.encoder.push_u32(pool_id);
600        self.encoder.push_i32(buffer.size as i32);
601        self.encoder.finish_message(self.shm_id, WL_SHM_CREATE_POOL);
602        self.send_message(Some(buffer.fd))?;
603
604        // Send wl_shm_pool.create_buffer
605        self.encoder.begin_message();
606        self.encoder.push_u32(buffer_id);
607        self.encoder.push_i32(0); // offset
608        self.encoder.push_i32(width as i32);
609        self.encoder.push_i32(height as i32);
610        self.encoder.push_i32((width * 4) as i32); // stride
611        self.encoder.push_u32(WL_SHM_FORMAT_ARGB8888);
612        self.encoder
613            .finish_message(pool_id, WL_SHM_POOL_CREATE_BUFFER);
614        self.send_message(None)?;
615
616        self.shm_buffer = Some(buffer);
617        Ok(())
618    }
619
620    /// Blocks until a specific `wl_callback` fires `done`.
621    fn roundtrip(&mut self, target_callback_id: u32) -> Result<(), String> {
622        let mut done = false;
623        let start = std::time::Instant::now();
624        while !done {
625            if start.elapsed() > std::time::Duration::from_secs(5) {
626                return Err("Wayland roundtrip timed out".to_string());
627            }
628            self.read_and_dispatch(&mut done, target_callback_id)?;
629            if !done {
630                std::thread::sleep(std::time::Duration::from_millis(2));
631            }
632        }
633        Ok(())
634    }
635
636    /// Reads available bytes from socket and dispatches Wayland events.
637    fn read_and_dispatch(
638        &mut self,
639        sync_done: &mut bool,
640        target_callback_id: u32,
641    ) -> Result<(), String> {
642        if let Some(ref mut stream) = self.stream {
643            let mut chunk = [0u8; 4096];
644            let mut peer_closed = false;
645            loop {
646                match stream.read(&mut chunk) {
647                    Ok(0) => {
648                        peer_closed = true;
649                        break;
650                    }
651                    Ok(n) => {
652                        self.read_buffer.extend_from_slice(&chunk[..n]);
653                    }
654                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
655                    Err(e) => return Err(format!("Wayland socket read error: {}", e)),
656                }
657            }
658
659            // Parse complete messages from buffer
660            while self.read_buffer.len() >= 8 {
661                let header = WaylandHeader::from_bytes(&self.read_buffer[..8]).unwrap();
662                let msg_len = header.size as usize;
663                if msg_len < 8 || self.read_buffer.len() < msg_len {
664                    break;
665                }
666
667                let payload = self.read_buffer[8..msg_len].to_vec();
668                self.read_buffer.drain(..msg_len);
669                self.handle_event(
670                    header.object_id,
671                    header.opcode,
672                    &payload,
673                    sync_done,
674                    target_callback_id,
675                );
676            }
677
678            if peer_closed && !*sync_done {
679                return Err("Wayland server closed connection".to_string());
680            }
681        }
682        Ok(())
683    }
684
685    /// Internal event dispatcher handling registry, ping/pong, configure, and input events.
686    fn handle_event(
687        &mut self,
688        object_id: u32,
689        opcode: u16,
690        payload: &[u8],
691        sync_done: &mut bool,
692        target_callback_id: u32,
693    ) {
694        // 1. Sync callback done event (opcode 0)
695        if object_id == target_callback_id && opcode == 0 {
696            *sync_done = true;
697            return;
698        }
699
700        // 2. Registry global advertisement (registry_id, opcode 0)
701        if object_id == self.registry_id && opcode == 0 {
702            let mut decoder = WaylandDecoder::new(payload);
703            if let (Some(name), Some(interface), _version) = (
704                decoder.read_u32(),
705                decoder.read_string(),
706                decoder.read_u32(),
707            ) {
708                match interface.as_str() {
709                    "wl_compositor" => self.globals.compositor_name = Some(name),
710                    "wl_shm" => self.globals.shm_name = Some(name),
711                    "xdg_wm_base" => self.globals.xdg_wm_base_name = Some(name),
712                    "wl_seat" => self.globals.seat_name = Some(name),
713                    _ => {}
714                }
715            }
716            return;
717        }
718
719        // 3. xdg_wm_base ping event (opcode 0)
720        if object_id == self.xdg_wm_base_id && opcode == 0 {
721            let mut decoder = WaylandDecoder::new(payload);
722            if let Some(serial) = decoder.read_u32() {
723                // Respond immediately with pong
724                self.encoder.begin_message();
725                self.encoder.push_u32(serial);
726                self.encoder
727                    .finish_message(self.xdg_wm_base_id, XDG_WM_BASE_PONG);
728                let _ = self.send_message(None);
729            }
730            return;
731        }
732
733        // 4. xdg_surface configure event (opcode 0)
734        if object_id == self.xdg_surface_id && opcode == 0 {
735            let mut decoder = WaylandDecoder::new(payload);
736            if let Some(serial) = decoder.read_u32() {
737                // Ack configure
738                self.encoder.begin_message();
739                self.encoder.push_u32(serial);
740                self.encoder
741                    .finish_message(self.xdg_surface_id, XDG_SURFACE_ACK_CONFIGURE);
742                let _ = self.send_message(None);
743                self.redraw_requested = true;
744            }
745            return;
746        }
747
748        // 5. xdg_toplevel configure event (opcode 0)
749        if object_id == self.xdg_toplevel_id && opcode == 0 {
750            let mut decoder = WaylandDecoder::new(payload);
751            if let (Some(w), Some(h)) = (decoder.read_i32(), decoder.read_i32()) {
752                if w > 0
753                    && h > 0
754                    && (w as u32 != self.config.width || h as u32 != self.config.height)
755                {
756                    let (width, height) = (w as u32, h as u32);
757                    self.config.width = width;
758                    self.config.height = height;
759                    let _ = self.recreate_shm_buffer(width, height);
760                    self.event_queue
761                        .push_back(PlatformEvent::WindowResized { width, height });
762                }
763            }
764            return;
765        }
766
767        // 6. xdg_toplevel close event (opcode 1)
768        if object_id == self.xdg_toplevel_id && opcode == 1 {
769            self.event_queue
770                .push_back(PlatformEvent::WindowCloseRequested);
771            return;
772        }
773
774        // 7. Pointer events
775        if object_id == self.pointer_id {
776            match opcode {
777                // enter(serial, surface, surface_x, surface_y)
778                0 => {
779                    let mut decoder = WaylandDecoder::new(payload);
780                    let _serial = decoder.read_u32();
781                    let _surface = decoder.read_u32();
782                    if let (Some(x), Some(y)) = (decoder.read_fixed(), decoder.read_fixed()) {
783                        let px = x as f32;
784                        let py = y as f32;
785                        self.cursor_pos = (px, py);
786                        self.event_queue
787                            .push_back(PlatformEvent::MouseMove { x: px, y: py });
788                    }
789                }
790                // leave(serial, surface)
791                1 => {
792                    self.event_queue.push_back(PlatformEvent::CursorLeft);
793                }
794                // motion(time, surface_x, surface_y)
795                2 => {
796                    let mut decoder = WaylandDecoder::new(payload);
797                    let _time = decoder.read_u32();
798                    if let (Some(x), Some(y)) = (decoder.read_fixed(), decoder.read_fixed()) {
799                        let px = x as f32;
800                        let py = y as f32;
801                        self.cursor_pos = (px, py);
802                        self.event_queue
803                            .push_back(PlatformEvent::MouseMove { x: px, y: py });
804                    }
805                }
806                // button(serial, time, button, state)
807                3 => {
808                    let mut decoder = WaylandDecoder::new(payload);
809                    let _serial = decoder.read_u32();
810                    if let Some(s) = _serial {
811                        self.last_serial = s;
812                    }
813                    let _time = decoder.read_u32();
814                    if let (Some(btn), Some(state)) = (decoder.read_u32(), decoder.read_u32()) {
815                        let button = match btn {
816                            0x110 => MouseButton::Left,
817                            0x111 => MouseButton::Right,
818                            0x112 => MouseButton::Middle,
819                            _ => MouseButton::Left,
820                        };
821                        let (x, y) = self.cursor_pos;
822                        if state == 1 {
823                            if button == MouseButton::Left {
824                                let now = std::time::Instant::now();
825                                if let Some((prev_time, px, py)) = self.last_click {
826                                    if now.duration_since(prev_time).as_millis() < 400
827                                        && (px - x).abs() < 6.0
828                                        && (py - y).abs() < 6.0
829                                    {
830                                        self.event_queue.push_back(PlatformEvent::DoubleClick {
831                                            button,
832                                            x,
833                                            y,
834                                        });
835                                        self.last_click = None;
836                                    } else {
837                                        self.last_click = Some((now, x, y));
838                                    }
839                                } else {
840                                    self.last_click = Some((now, x, y));
841                                }
842                            }
843                            self.event_queue
844                                .push_back(PlatformEvent::MouseDown { x, y, button });
845                        } else {
846                            self.event_queue
847                                .push_back(PlatformEvent::MouseUp { x, y, button });
848                        }
849                    }
850                }
851                // axis(time, axis, value)
852                4 => {
853                    let mut decoder = WaylandDecoder::new(payload);
854                    let _time = decoder.read_u32();
855                    if let (Some(axis), Some(value)) = (decoder.read_u32(), decoder.read_fixed()) {
856                        let (delta_x, delta_y) = if axis == 0 {
857                            (0.0, value as f32)
858                        } else {
859                            (value as f32, 0.0)
860                        };
861                        self.event_queue.push_back(PlatformEvent::Scroll {
862                            delta_x,
863                            delta_y,
864                            is_momentum: false,
865                        });
866                    }
867                }
868                _ => {}
869            }
870            return;
871        }
872
873        // 8. Keyboard key event
874        if object_id == self.keyboard_id && opcode == 3 {
875            let mut decoder = WaylandDecoder::new(payload);
876            let _serial = decoder.read_u32();
877            let _time = decoder.read_u32();
878            if let (Some(key), Some(state)) = (decoder.read_u32(), decoder.read_u32()) {
879                let (key_code, ch) = match key {
880                    1 => (KeyCode::Escape, None),
881                    2 => (KeyCode::Digit1, Some('1')),
882                    3 => (KeyCode::Digit2, Some('2')),
883                    4 => (KeyCode::Digit3, Some('3')),
884                    5 => (KeyCode::Digit4, Some('4')),
885                    6 => (KeyCode::Digit5, Some('5')),
886                    7 => (KeyCode::Digit6, Some('6')),
887                    8 => (KeyCode::Digit7, Some('7')),
888                    9 => (KeyCode::Digit8, Some('8')),
889                    10 => (KeyCode::Digit9, Some('9')),
890                    11 => (KeyCode::Digit0, Some('0')),
891                    12 => (KeyCode::Minus, Some('-')),
892                    13 => (KeyCode::Equals, Some('=')),
893                    14 => (KeyCode::Backspace, None),
894                    15 => (KeyCode::Tab, Some('\t')),
895                    16 => (KeyCode::KeyQ, Some('q')),
896                    17 => (KeyCode::KeyW, Some('w')),
897                    18 => (KeyCode::KeyE, Some('e')),
898                    19 => (KeyCode::KeyR, Some('r')),
899                    20 => (KeyCode::KeyT, Some('t')),
900                    21 => (KeyCode::KeyY, Some('y')),
901                    22 => (KeyCode::KeyU, Some('u')),
902                    23 => (KeyCode::KeyI, Some('i')),
903                    24 => (KeyCode::KeyO, Some('o')),
904                    25 => (KeyCode::KeyP, Some('p')),
905                    26 => (KeyCode::BracketLeft, Some('[')),
906                    27 => (KeyCode::BracketRight, Some(']')),
907                    28 => (KeyCode::Enter, Some('\n')),
908                    30 => (KeyCode::KeyA, Some('a')),
909                    31 => (KeyCode::KeyS, Some('s')),
910                    32 => (KeyCode::KeyD, Some('d')),
911                    33 => (KeyCode::KeyF, Some('f')),
912                    34 => (KeyCode::KeyG, Some('g')),
913                    35 => (KeyCode::KeyH, Some('h')),
914                    36 => (KeyCode::KeyJ, Some('j')),
915                    37 => (KeyCode::KeyK, Some('k')),
916                    38 => (KeyCode::KeyL, Some('l')),
917                    39 => (KeyCode::Semicolon, Some(';')),
918                    40 => (KeyCode::Quote, Some('\'')),
919                    41 => (KeyCode::Backquote, Some('`')),
920                    43 => (KeyCode::Backslash, Some('\\')),
921                    44 => (KeyCode::KeyZ, Some('z')),
922                    45 => (KeyCode::KeyX, Some('x')),
923                    46 => (KeyCode::KeyC, Some('c')),
924                    47 => (KeyCode::KeyV, Some('v')),
925                    48 => (KeyCode::KeyB, Some('b')),
926                    49 => (KeyCode::KeyN, Some('n')),
927                    50 => (KeyCode::KeyM, Some('m')),
928                    51 => (KeyCode::Comma, Some(',')),
929                    52 => (KeyCode::Period, Some('.')),
930                    53 => (KeyCode::Slash, Some('/')),
931                    57 => (KeyCode::Space, Some(' ')),
932                    103 => (KeyCode::ArrowUp, None),
933                    105 => (KeyCode::ArrowLeft, None),
934                    106 => (KeyCode::ArrowRight, None),
935                    108 => (KeyCode::ArrowDown, None),
936                    111 => (KeyCode::Delete, None),
937                    _ => (KeyCode::Unknown, None),
938                };
939                if state == 1 {
940                    self.event_queue.push_back(PlatformEvent::KeyDown {
941                        key: key_code,
942                        modifiers: Modifiers::default(),
943                    });
944                    if let Some(c) = ch {
945                        self.event_queue
946                            .push_back(PlatformEvent::ReceivedCharacter(c));
947                    }
948                } else {
949                    self.event_queue.push_back(PlatformEvent::KeyUp {
950                        key: key_code,
951                        modifiers: Modifiers::default(),
952                    });
953                }
954            }
955        }
956    }
957
958    /// Presents a 32-bit BGRA buffer directly to the Wayland surface via `wl_shm`.
959    pub fn present_bgra(&mut self, pixels: &[u8], width: u32, height: u32) -> Result<(), String> {
960        if let Some(ref mut shm) = self.shm_buffer {
961            if shm.width != width || shm.height != height {
962                self.recreate_shm_buffer(width, height)?;
963            }
964        } else {
965            self.recreate_shm_buffer(width, height)?;
966        }
967
968        if let Some(ref mut shm) = self.shm_buffer {
969            shm.write_pixels(pixels);
970
971            // Attach buffer
972            self.encoder.begin_message();
973            self.encoder.push_u32(shm.buffer_id);
974            self.encoder.push_i32(0); // x
975            self.encoder.push_i32(0); // y
976            self.encoder
977                .finish_message(self.surface_id, WL_SURFACE_ATTACH);
978            self.send_message(None)?;
979
980            // Damage surface
981            self.encoder.begin_message();
982            self.encoder.push_i32(0);
983            self.encoder.push_i32(0);
984            self.encoder.push_i32(width as i32);
985            self.encoder.push_i32(height as i32);
986            self.encoder
987                .finish_message(self.surface_id, WL_SURFACE_DAMAGE);
988            self.send_message(None)?;
989
990            // Commit surface
991            self.encoder.begin_message();
992            self.encoder
993                .finish_message(self.surface_id, WL_SURFACE_COMMIT);
994            self.send_message(None)?;
995        }
996
997        Ok(())
998    }
999
1000    /// Pumps incoming Wayland socket events and returns translated platform events.
1001    pub fn poll_native_events(&mut self) -> Vec<PlatformEvent> {
1002        let mut dummy = false;
1003        let _ = self.read_and_dispatch(&mut dummy, 0);
1004        self.event_queue.drain(..).collect()
1005    }
1006}
1007
1008impl PlatformWindow for WaylandWindow {
1009    fn title(&self) -> &str {
1010        &self.config.title
1011    }
1012
1013    fn set_title(&mut self, title: &str) {
1014        self.config.title = title.to_string();
1015        self.encoder.begin_message();
1016        self.encoder.push_string(title);
1017        self.encoder
1018            .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_TITLE);
1019        let _ = self.send_message(None);
1020    }
1021
1022    fn size(&self) -> (u32, u32) {
1023        (self.config.width, self.config.height)
1024    }
1025
1026    fn set_size(&mut self, width: u32, height: u32) {
1027        self.config.width = width;
1028        self.config.height = height;
1029        let _ = self.recreate_shm_buffer(width, height);
1030        self.push_event(PlatformEvent::WindowResized { width, height });
1031    }
1032
1033    fn scale_factor(&self) -> f32 {
1034        self.scale_factor
1035    }
1036
1037    fn set_scale_factor(&mut self, scale_factor: f32) {
1038        self.scale_factor = scale_factor;
1039        self.push_event(PlatformEvent::ScaleFactorChanged { scale_factor });
1040    }
1041
1042    fn mode(&self) -> WindowMode {
1043        self.config.mode
1044    }
1045
1046    fn set_mode(&mut self, mode: WindowMode) {
1047        let prev = self.config.mode;
1048        self.config.mode = mode;
1049        match mode {
1050            WindowMode::Maximized => {
1051                self.encoder.begin_message();
1052                self.encoder
1053                    .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_MAXIMIZED);
1054                let _ = self.send_message(None);
1055                if prev != WindowMode::Maximized {
1056                    self.push_event(PlatformEvent::WindowMaximized(true));
1057                }
1058            }
1059            WindowMode::Minimized => {
1060                self.encoder.begin_message();
1061                self.encoder
1062                    .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_MINIMIZED);
1063                let _ = self.send_message(None);
1064            }
1065            WindowMode::Windowed => {
1066                self.encoder.begin_message();
1067                self.encoder
1068                    .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_UNSET_MAXIMIZED);
1069                let _ = self.send_message(None);
1070                if prev == WindowMode::Maximized {
1071                    self.push_event(PlatformEvent::WindowMaximized(false));
1072                }
1073            }
1074            _ => {}
1075        }
1076    }
1077
1078    fn is_focused(&self) -> bool {
1079        self.is_focused
1080    }
1081
1082    fn set_focused(&mut self, focused: bool) {
1083        self.is_focused = focused;
1084        self.push_event(PlatformEvent::WindowFocused(focused));
1085    }
1086
1087    fn cursor(&self) -> CursorIcon {
1088        self.cursor
1089    }
1090
1091    fn set_cursor(&mut self, cursor: CursorIcon) {
1092        self.cursor = cursor;
1093    }
1094
1095    fn request_redraw(&mut self) {
1096        self.redraw_requested = true;
1097    }
1098
1099    fn is_redraw_requested(&self) -> bool {
1100        self.redraw_requested
1101    }
1102
1103    fn poll_events(&mut self) -> Vec<PlatformEvent> {
1104        self.poll_native_events()
1105    }
1106
1107    fn push_event(&mut self, event: PlatformEvent) {
1108        self.event_queue.push_back(event);
1109    }
1110
1111    fn begin_window_drag(&mut self, _x: f32, _y: f32) {
1112        if self.seat_id != 0 {
1113            self.encoder.begin_message();
1114            self.encoder.push_u32(self.seat_id);
1115            self.encoder.push_u32(self.last_serial);
1116            self.encoder
1117                .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_MOVE);
1118            let _ = self.send_message(None);
1119        }
1120    }
1121
1122    fn begin_window_resize(&mut self, edge: crate::csd::CsdHitZone, _x: f32, _y: f32) {
1123        if self.seat_id != 0 {
1124            if let Some(wayland_edge) = edge.to_wayland_resize_edge() {
1125                self.encoder.begin_message();
1126                self.encoder.push_u32(self.seat_id);
1127                self.encoder.push_u32(self.last_serial);
1128                self.encoder.push_u32(wayland_edge);
1129                self.encoder
1130                    .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_RESIZE);
1131                let _ = self.send_message(None);
1132            }
1133        }
1134    }
1135}
1136
1137impl crate::window::NativeSurfaceWindow for WaylandWindow {
1138    fn present_surface(
1139        &mut self,
1140        pixels: &[u8],
1141        width: u32,
1142        height: u32,
1143    ) -> Result<(), crate::surface::PresentError> {
1144        self.present_bgra(pixels, width, height)
1145            .map_err(crate::surface::PresentError::Custom)
1146    }
1147}
1148
1149/// Pure-Rust Wayland native event loop driving event dispatch and frame pacing.
1150pub struct WaylandEventLoop {
1151    pub window: WaylandWindow,
1152    pub control: EventLoopControl,
1153}
1154
1155impl WaylandEventLoop {
1156    /// Creates a new event loop driving the given Wayland window.
1157    pub fn new(window: WaylandWindow) -> Self {
1158        Self {
1159            window,
1160            control: EventLoopControl::Poll,
1161        }
1162    }
1163}
1164
1165impl EventLoop for WaylandEventLoop {
1166    fn run<F>(&mut self, mut handler: F)
1167    where
1168        F: FnMut(PlatformEvent, &mut EventLoopControl),
1169    {
1170        while self.control != EventLoopControl::Exit {
1171            let events = self.window.poll_native_events();
1172            for event in events {
1173                handler(event, &mut self.control);
1174                if self.control == EventLoopControl::Exit {
1175                    break;
1176                }
1177            }
1178
1179            if self.window.is_redraw_requested() {
1180                self.window.redraw_requested = false;
1181                handler(PlatformEvent::RedrawRequested, &mut self.control);
1182            }
1183
1184            match self.control {
1185                EventLoopControl::Poll => std::thread::yield_now(),
1186                EventLoopControl::Wait => std::thread::sleep(std::time::Duration::from_millis(150)),
1187                EventLoopControl::WaitUntil(instant) => {
1188                    let now = std::time::Instant::now();
1189                    if let Some(dur) = instant.checked_duration_since(now) {
1190                        std::thread::sleep(dur.min(std::time::Duration::from_millis(150)));
1191                    }
1192                }
1193                EventLoopControl::Exit => break,
1194            }
1195        }
1196    }
1197}