1#![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
20pub const WL_DISPLAY_ID: u32 = 1;
22
23pub const WL_DISPLAY_SYNC: u16 = 0;
25pub const WL_DISPLAY_GET_REGISTRY: u16 = 1;
26
27pub const WL_REGISTRY_BIND: u16 = 0;
29
30pub const WL_COMPOSITOR_CREATE_SURFACE: u16 = 0;
32
33pub const WL_SHM_CREATE_POOL: u16 = 0;
35pub const WL_SHM_FORMAT_ARGB8888: u32 = 0;
36pub const WL_SHM_FORMAT_XRGB8888: u32 = 1;
37
38pub 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
43pub 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
49pub 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
54pub const XDG_SURFACE_DESTROY: u16 = 0;
56pub const XDG_SURFACE_GET_TOPLEVEL: u16 = 1;
57pub const XDG_SURFACE_ACK_CONFIGURE: u16 = 4;
58
59pub 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
69pub const WL_SEAT_GET_POINTER: u16 = 0;
71pub const WL_SEAT_GET_KEYBOARD: u16 = 1;
72
73#[derive(Debug, Default)]
75pub struct WaylandEncoder {
76 buffer: Vec<u8>,
77}
78
79impl WaylandEncoder {
80 pub fn new() -> Self {
82 Self {
83 buffer: Vec::with_capacity(128),
84 }
85 }
86
87 pub fn clear(&mut self) {
89 self.buffer.clear();
90 }
91
92 pub fn as_bytes(&self) -> &[u8] {
94 &self.buffer
95 }
96
97 pub fn begin_message(&mut self) {
99 self.buffer.clear();
100 self.buffer.extend_from_slice(&[0u8; 8]);
101 }
102
103 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 pub fn push_u32(&mut self, val: u32) {
116 self.buffer.extend_from_slice(&val.to_ne_bytes());
117 }
118
119 pub fn push_i32(&mut self, val: i32) {
121 self.buffer.extend_from_slice(&val.to_ne_bytes());
122 }
123
124 pub fn push_fixed(&mut self, val: f64) {
126 let fixed = (val * 256.0) as i32;
127 self.push_i32(fixed);
128 }
129
130 pub fn push_string(&mut self, s: &str) {
132 let bytes = s.as_bytes();
133 let len = (bytes.len() + 1) as u32; self.push_u32(len);
135 self.buffer.extend_from_slice(bytes);
136 self.buffer.push(0); while !self.buffer.len().is_multiple_of(4) {
139 self.buffer.push(0);
140 }
141 }
142}
143
144#[derive(Debug)]
146pub struct WaylandDecoder<'a> {
147 data: &'a [u8],
148 offset: usize,
149}
150
151impl<'a> WaylandDecoder<'a> {
152 pub fn new(data: &'a [u8]) -> Self {
154 Self { data, offset: 0 }
155 }
156
157 pub fn remaining(&self) -> usize {
159 self.data.len().saturating_sub(self.offset)
160 }
161
162 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 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 pub fn read_fixed(&mut self) -> Option<f64> {
184 self.read_i32().map(|fixed| fixed as f64 / 256.0)
185 }
186
187 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
206fn 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
251fn 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 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
282pub 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 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 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#[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
353pub 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 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 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 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 fn allocate_id(&mut self) -> u32 {
432 let id = self.next_id;
433 self.next_id += 1;
434 id
435 }
436
437 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 fn init_wayland_connection(&mut self) -> Result<(), String> {
453 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 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 self.roundtrip(sync_cb)?;
470
471 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); 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); 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); 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); 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 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 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 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 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 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 self.encoder.begin_message();
581 self.encoder
582 .finish_message(self.surface_id, WL_SURFACE_COMMIT);
583 self.send_message(None)?;
584
585 self.recreate_shm_buffer(self.config.width, self.config.height)?;
587
588 Ok(())
589 }
590
591 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 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 self.encoder.begin_message();
606 self.encoder.push_u32(buffer_id);
607 self.encoder.push_i32(0); self.encoder.push_i32(width as i32);
609 self.encoder.push_i32(height as i32);
610 self.encoder.push_i32((width * 4) as i32); 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 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 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 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 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 if object_id == target_callback_id && opcode == 0 {
696 *sync_done = true;
697 return;
698 }
699
700 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 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 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 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 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 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 if object_id == self.xdg_toplevel_id && opcode == 1 {
769 self.event_queue
770 .push_back(PlatformEvent::WindowCloseRequested);
771 return;
772 }
773
774 if object_id == self.pointer_id {
776 match opcode {
777 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 1 => {
792 self.event_queue.push_back(PlatformEvent::CursorLeft);
793 }
794 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 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 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 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 14 => (KeyCode::Backspace, None),
892 15 => (KeyCode::Tab, Some('\t')),
893 16 => (KeyCode::KeyQ, Some('q')),
894 17 => (KeyCode::KeyW, Some('w')),
895 18 => (KeyCode::KeyE, Some('e')),
896 19 => (KeyCode::KeyR, Some('r')),
897 20 => (KeyCode::KeyT, Some('t')),
898 21 => (KeyCode::KeyY, Some('y')),
899 22 => (KeyCode::KeyU, Some('u')),
900 23 => (KeyCode::KeyI, Some('i')),
901 24 => (KeyCode::KeyO, Some('o')),
902 25 => (KeyCode::KeyP, Some('p')),
903 28 => (KeyCode::Enter, Some('\n')),
904 30 => (KeyCode::KeyA, Some('a')),
905 31 => (KeyCode::KeyS, Some('s')),
906 32 => (KeyCode::KeyD, Some('d')),
907 33 => (KeyCode::KeyF, Some('f')),
908 34 => (KeyCode::KeyG, Some('g')),
909 35 => (KeyCode::KeyH, Some('h')),
910 36 => (KeyCode::KeyJ, Some('j')),
911 37 => (KeyCode::KeyK, Some('k')),
912 38 => (KeyCode::KeyL, Some('l')),
913 44 => (KeyCode::KeyZ, Some('z')),
914 45 => (KeyCode::KeyX, Some('x')),
915 46 => (KeyCode::KeyC, Some('c')),
916 47 => (KeyCode::KeyV, Some('v')),
917 48 => (KeyCode::KeyB, Some('b')),
918 49 => (KeyCode::KeyN, Some('n')),
919 50 => (KeyCode::KeyM, Some('m')),
920 57 => (KeyCode::Space, Some(' ')),
921 103 => (KeyCode::ArrowUp, None),
922 105 => (KeyCode::ArrowLeft, None),
923 106 => (KeyCode::ArrowRight, None),
924 108 => (KeyCode::ArrowDown, None),
925 111 => (KeyCode::Delete, None),
926 _ => (KeyCode::Unknown, None),
927 };
928 if state == 1 {
929 self.event_queue.push_back(PlatformEvent::KeyDown {
930 key: key_code,
931 modifiers: Modifiers::default(),
932 });
933 if let Some(c) = ch {
934 self.event_queue
935 .push_back(PlatformEvent::ReceivedCharacter(c));
936 }
937 } else {
938 self.event_queue.push_back(PlatformEvent::KeyUp {
939 key: key_code,
940 modifiers: Modifiers::default(),
941 });
942 }
943 }
944 }
945 }
946
947 pub fn present_bgra(&mut self, pixels: &[u8], width: u32, height: u32) -> Result<(), String> {
949 if let Some(ref mut shm) = self.shm_buffer {
950 if shm.width != width || shm.height != height {
951 self.recreate_shm_buffer(width, height)?;
952 }
953 } else {
954 self.recreate_shm_buffer(width, height)?;
955 }
956
957 if let Some(ref mut shm) = self.shm_buffer {
958 shm.write_pixels(pixels);
959
960 self.encoder.begin_message();
962 self.encoder.push_u32(shm.buffer_id);
963 self.encoder.push_i32(0); self.encoder.push_i32(0); self.encoder
966 .finish_message(self.surface_id, WL_SURFACE_ATTACH);
967 self.send_message(None)?;
968
969 self.encoder.begin_message();
971 self.encoder.push_i32(0);
972 self.encoder.push_i32(0);
973 self.encoder.push_i32(width as i32);
974 self.encoder.push_i32(height as i32);
975 self.encoder
976 .finish_message(self.surface_id, WL_SURFACE_DAMAGE);
977 self.send_message(None)?;
978
979 self.encoder.begin_message();
981 self.encoder
982 .finish_message(self.surface_id, WL_SURFACE_COMMIT);
983 self.send_message(None)?;
984 }
985
986 Ok(())
987 }
988
989 pub fn poll_native_events(&mut self) -> Vec<PlatformEvent> {
991 let mut dummy = false;
992 let _ = self.read_and_dispatch(&mut dummy, 0);
993 self.event_queue.drain(..).collect()
994 }
995}
996
997impl PlatformWindow for WaylandWindow {
998 fn title(&self) -> &str {
999 &self.config.title
1000 }
1001
1002 fn set_title(&mut self, title: &str) {
1003 self.config.title = title.to_string();
1004 self.encoder.begin_message();
1005 self.encoder.push_string(title);
1006 self.encoder
1007 .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_TITLE);
1008 let _ = self.send_message(None);
1009 }
1010
1011 fn size(&self) -> (u32, u32) {
1012 (self.config.width, self.config.height)
1013 }
1014
1015 fn set_size(&mut self, width: u32, height: u32) {
1016 self.config.width = width;
1017 self.config.height = height;
1018 let _ = self.recreate_shm_buffer(width, height);
1019 self.push_event(PlatformEvent::WindowResized { width, height });
1020 }
1021
1022 fn scale_factor(&self) -> f32 {
1023 self.scale_factor
1024 }
1025
1026 fn set_scale_factor(&mut self, scale_factor: f32) {
1027 self.scale_factor = scale_factor;
1028 self.push_event(PlatformEvent::ScaleFactorChanged { scale_factor });
1029 }
1030
1031 fn mode(&self) -> WindowMode {
1032 self.config.mode
1033 }
1034
1035 fn set_mode(&mut self, mode: WindowMode) {
1036 let prev = self.config.mode;
1037 self.config.mode = mode;
1038 match mode {
1039 WindowMode::Maximized => {
1040 self.encoder.begin_message();
1041 self.encoder
1042 .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_MAXIMIZED);
1043 let _ = self.send_message(None);
1044 if prev != WindowMode::Maximized {
1045 self.push_event(PlatformEvent::WindowMaximized(true));
1046 }
1047 }
1048 WindowMode::Minimized => {
1049 self.encoder.begin_message();
1050 self.encoder
1051 .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_SET_MINIMIZED);
1052 let _ = self.send_message(None);
1053 }
1054 WindowMode::Windowed => {
1055 self.encoder.begin_message();
1056 self.encoder
1057 .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_UNSET_MAXIMIZED);
1058 let _ = self.send_message(None);
1059 if prev == WindowMode::Maximized {
1060 self.push_event(PlatformEvent::WindowMaximized(false));
1061 }
1062 }
1063 _ => {}
1064 }
1065 }
1066
1067 fn is_focused(&self) -> bool {
1068 self.is_focused
1069 }
1070
1071 fn set_focused(&mut self, focused: bool) {
1072 self.is_focused = focused;
1073 self.push_event(PlatformEvent::WindowFocused(focused));
1074 }
1075
1076 fn cursor(&self) -> CursorIcon {
1077 self.cursor
1078 }
1079
1080 fn set_cursor(&mut self, cursor: CursorIcon) {
1081 self.cursor = cursor;
1082 }
1083
1084 fn request_redraw(&mut self) {
1085 self.redraw_requested = true;
1086 }
1087
1088 fn is_redraw_requested(&self) -> bool {
1089 self.redraw_requested
1090 }
1091
1092 fn poll_events(&mut self) -> Vec<PlatformEvent> {
1093 self.poll_native_events()
1094 }
1095
1096 fn push_event(&mut self, event: PlatformEvent) {
1097 self.event_queue.push_back(event);
1098 }
1099
1100 fn begin_window_drag(&mut self, _x: f32, _y: f32) {
1101 if self.seat_id != 0 {
1102 self.encoder.begin_message();
1103 self.encoder.push_u32(self.seat_id);
1104 self.encoder.push_u32(self.last_serial);
1105 self.encoder
1106 .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_MOVE);
1107 let _ = self.send_message(None);
1108 }
1109 }
1110
1111 fn begin_window_resize(&mut self, edge: crate::csd::CsdHitZone, _x: f32, _y: f32) {
1112 if self.seat_id != 0 {
1113 if let Some(wayland_edge) = edge.to_wayland_resize_edge() {
1114 self.encoder.begin_message();
1115 self.encoder.push_u32(self.seat_id);
1116 self.encoder.push_u32(self.last_serial);
1117 self.encoder.push_u32(wayland_edge);
1118 self.encoder
1119 .finish_message(self.xdg_toplevel_id, XDG_TOPLEVEL_RESIZE);
1120 let _ = self.send_message(None);
1121 }
1122 }
1123 }
1124}
1125
1126impl crate::window::NativeSurfaceWindow for WaylandWindow {
1127 fn present_surface(
1128 &mut self,
1129 pixels: &[u8],
1130 width: u32,
1131 height: u32,
1132 ) -> Result<(), crate::surface::PresentError> {
1133 self.present_bgra(pixels, width, height)
1134 .map_err(crate::surface::PresentError::Custom)
1135 }
1136}
1137
1138pub struct WaylandEventLoop {
1140 pub window: WaylandWindow,
1141 pub control: EventLoopControl,
1142}
1143
1144impl WaylandEventLoop {
1145 pub fn new(window: WaylandWindow) -> Self {
1147 Self {
1148 window,
1149 control: EventLoopControl::Poll,
1150 }
1151 }
1152}
1153
1154impl EventLoop for WaylandEventLoop {
1155 fn run<F>(&mut self, mut handler: F)
1156 where
1157 F: FnMut(PlatformEvent, &mut EventLoopControl),
1158 {
1159 while self.control != EventLoopControl::Exit {
1160 let events = self.window.poll_native_events();
1161 for event in events {
1162 handler(event, &mut self.control);
1163 if self.control == EventLoopControl::Exit {
1164 break;
1165 }
1166 }
1167
1168 if self.window.is_redraw_requested() {
1169 self.window.redraw_requested = false;
1170 handler(PlatformEvent::RedrawRequested, &mut self.control);
1171 }
1172
1173 match self.control {
1174 EventLoopControl::Poll => std::thread::yield_now(),
1175 EventLoopControl::Wait => std::thread::sleep(std::time::Duration::from_millis(150)),
1176 EventLoopControl::WaitUntil(instant) => {
1177 let now = std::time::Instant::now();
1178 if let Some(dur) = instant.checked_duration_since(now) {
1179 std::thread::sleep(dur.min(std::time::Duration::from_millis(150)));
1180 }
1181 }
1182 EventLoopControl::Exit => break,
1183 }
1184 }
1185 }
1186}