Skip to main content

velox_engine/platform/wayland/
mod.rs

1//! 纯 Wayland 客户端平台后端 `velox_engine::platform::wayland`(不依赖 `winit` 或任何 X11 库)。
2//!
3//! 模块职责划分:
4//! - `wire`:Wayland 二进制协议对象、事件与 UNIX Socket 线协议客户端状态机;
5//! - `mod`:[`WaylandPlatform`] 双缓冲驱动与 [`Platform`] / [`PlatformSurface`] 实现。
6
7pub mod dmabuf;
8#[cfg(unix)]
9mod unix_socket;
10mod wire;
11
12pub use dmabuf::{DmaBufPlaneDesc, WaylandDmaBufDriver, WaylandDmaBufPacket};
13
14use std::string::String;
15use std::time::{Duration, Instant};
16use std::vec::Vec;
17
18pub use super::shm_driver::{
19    decode_linux_keycode, decode_linux_modifier, write_uncompressed_png, ShmSlot, ShmSurfaceDriver,
20    SoftwareSurfaceDriver, WaylandSurfaceDriver, WlBuffer, WlSurface,
21};
22pub use wire::{
23    SurfaceId, WaylandSurfaceRole, WaylandWireEvent, WaylandWireState, WlClientEvent,
24};
25use crate::prelude::*;
26
27/// 纯 Wayland 客户端平台(实现 [`Platform`] 与 [`PlatformSurface`],不依赖 `winit`)。
28///
29/// 支持两种工作模式:
30/// - **内存缓冲/自定义传输模式(默认)**:`WaylandPlatform::new` 仅初始化 `wl_shm` 双缓冲与 `WaylandWireState`,不会隐式连接宿主机的 `$WAYLAND_DISPLAY`;
31/// - **外部 Wayland 合成器 UNIX 套接字直连模式**:通过 [`WaylandPlatform::new_connected`]、[`WaylandPlatform::connect_to_compositor`] 或设置环境变量 `VELOX_WAYLAND_AUTO_CONNECT=1` 显式连接真实 Wayland 合成器。
32pub struct WaylandPlatform {
33    pub role: WaylandSurfaceRole,
34    width: usize,
35    height: usize,
36    start_instant: Instant,
37    pub shm_driver: WaylandSurfaceDriver,
38    pub wl_surface: WlSurface,
39    pub wire_state: WaylandWireState,
40    pub pending_events: Vec<WaylandWireEvent>,
41    pub close_requested: bool,
42    #[cfg(unix)]
43    compositor_conn: Option<unix_socket::WaylandCompositorConnection>,
44}
45
46impl WaylandPlatform {
47    /// 创建指定 `WaylandSurfaceRole` 与初始尺寸的纯 Wayland 客户端平台。
48    ///
49    /// 默认工作于无阻塞内存缓冲模式;若设置了 `VELOX_WAYLAND_AUTO_CONNECT=1` 或调用 [`Self::connect_to_compositor`],则连接 `$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY`。
50    pub fn new(role: WaylandSurfaceRole, width: usize, height: usize) -> Self {
51        let w = width.max(1);
52        let h = height.max(1);
53        #[allow(unused_mut)]
54        let mut wire_state = WaylandWireState::new();
55        #[cfg(unix)]
56        let compositor_conn = if std::env::var("VELOX_WAYLAND_AUTO_CONNECT").as_deref() == Ok("1") {
57            unix_socket::WaylandCompositorConnection::try_connect(
58                &role,
59                w,
60                h,
61                &mut wire_state,
62            )
63        } else {
64            None
65        };
66        Self {
67            role,
68            width: w,
69            height: h,
70            start_instant: Instant::now(),
71            shm_driver: WaylandSurfaceDriver::new(w, h),
72            wl_surface: WlSurface::new(),
73            wire_state,
74            pending_events: Vec::new(),
75            close_requested: false,
76            #[cfg(unix)]
77            compositor_conn,
78        }
79    }
80
81    /// 创建并显式尝试连接系统 `$WAYLAND_DISPLAY` 合成器套接字的客户端平台。
82    pub fn new_connected(role: WaylandSurfaceRole, width: usize, height: usize) -> Self {
83        let mut plat = Self::new(role, width, height);
84        let _ = plat.connect_to_compositor();
85        plat
86    }
87
88    /// 显式尝试连接 `$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY` 合成器 UNIX 套接字。
89    pub fn connect_to_compositor(&mut self) -> bool {
90        #[cfg(unix)]
91        {
92            if self.compositor_conn.is_none() {
93                self.compositor_conn = unix_socket::WaylandCompositorConnection::try_connect(
94                    &self.role,
95                    self.width,
96                    self.height,
97                    &mut self.wire_state,
98                );
99            }
100            self.compositor_conn.is_some()
101        }
102        #[cfg(not(unix))]
103        {
104            false
105        }
106    }
107
108    /// 是否已连接至真实的系统 Wayland 合成器 UNIX 套接字(`$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY`)。
109    #[inline]
110    pub fn is_connected_to_compositor(&self) -> bool {
111        #[cfg(unix)]
112        {
113            self.compositor_conn.is_some()
114        }
115        #[cfg(not(unix))]
116        {
117            false
118        }
119    }
120
121    /// 创建 `zwlr_layer_shell_v1` Wayland 客户端平台。
122    pub fn new_layer_shell(
123        namespace: impl Into<String>,
124        width: usize,
125        height: usize,
126        exclusive_zone: i16,
127    ) -> Self {
128        Self::new(
129            WaylandSurfaceRole::LayerShell {
130                namespace: namespace.into(),
131                exclusive_zone,
132            },
133            width,
134            height,
135        )
136    }
137
138    /// 创建 `zxdg_toplevel_decoration_v1` / `wl_subsurface` Wayland 客户端平台。
139    pub fn new_subsurface_decoration(parent_surface_id: u32, width: usize, height: usize) -> Self {
140        Self::new(
141            WaylandSurfaceRole::SubSurfaceDecoration { parent_surface_id },
142            width,
143            height,
144        )
145    }
146
147    /// 创建标准 `xdg_toplevel` 应用窗口的 Wayland 客户端平台。
148    pub fn new_xdg_toplevel(
149        title: impl Into<String>,
150        app_id: impl Into<String>,
151        width: usize,
152        height: usize,
153    ) -> Self {
154        Self::new(
155            WaylandSurfaceRole::XdgToplevel {
156                title: title.into(),
157                app_id: app_id.into(),
158            },
159            width,
160            height,
161        )
162    }
163
164    /// 向客户端注入原始 Wayland Wire 协议字节流并处理事件(可用于合成器直连或协议单元测试)。
165    pub fn feed_wire_bytes(&mut self, engine: &mut VeloxEngine, bytes: &[u8]) {
166        let evs = self.wire_state.feed_incoming_bytes(bytes);
167        self.process_wire_events(engine, evs);
168    }
169
170    fn process_wire_events(&mut self, engine: &mut VeloxEngine, events: Vec<WaylandWireEvent>) {
171        for ev in events {
172            match &ev {
173                WaylandWireEvent::Configure { width, height, .. } => {
174                    if *width > 0 && *height > 0 && (*width != self.width || *height != self.height)
175                    {
176                        self.handle_configure(engine, *width as i16, *height as i16);
177                    }
178                }
179                WaylandWireEvent::BufferReleased { buffer_id } => {
180                    self.shm_driver.release_buffer(*buffer_id);
181                }
182                WaylandWireEvent::SeatInput(input_ev) => {
183                    if matches!(input_ev, InputEvent::PointerDown { .. }) {
184                        engine.set_pointer_kind(PointerKind::Mouse);
185                    }
186                    engine.dispatch_event(*input_ev);
187                }
188                WaylandWireEvent::CloseRequested => {
189                    self.close_requested = true;
190                }
191                _ => {}
192            }
193            self.pending_events.push(ev);
194        }
195    }
196
197    /// 响应合成器下发的 `configure(width, height)` 事件,调整 `VeloxEngine` 视口与 `wl_shm` 缓冲池。
198    pub fn handle_configure(&mut self, engine: &mut VeloxEngine, width: i16, height: i16) {
199        let w = width.max(16) as usize;
200        let h = height.max(16) as usize;
201        self.width = w;
202        self.height = h;
203        engine.resize(w as i16, h as i16);
204        self.shm_driver.resize(w, h);
205        self.wl_surface = WlSurface::new();
206        #[cfg(unix)]
207        if let Some(conn) = &mut self.compositor_conn {
208            conn.resize_pool(w, h, &mut self.wire_state);
209        } else {
210            self.wire_state.encode_destroy_double_buffers();
211            self.wire_state.encode_create_double_buffers(w, h);
212        }
213        #[cfg(not(unix))]
214        {
215            self.wire_state.encode_destroy_double_buffers();
216            self.wire_state.encode_create_double_buffers(w, h);
217        }
218    }
219
220    /// 获取当前前台已提交的 `wl_shm` 像素切片。
221    #[inline]
222    pub fn front_pixels(&self) -> &[Xrgb8888] {
223        self.shm_driver.front_pixels()
224    }
225
226    /// 配置桌面渲染后端类型(`Wgpu` 或 `Software`)。
227    #[inline]
228    pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
229        self.shm_driver.set_backend(backend);
230        self
231    }
232
233    /// 动态切换桌面渲染后端类型。
234    #[inline]
235    pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
236        self.shm_driver.set_backend(backend);
237    }
238
239    /// 返回当前激活的桌面渲染后端类型。
240    #[inline]
241    pub const fn backend(&self) -> super::DesktopRenderBackend {
242        self.shm_driver.backend()
243    }
244
245    /// 获取最近一次 `wl_surface.commit` 提交的局部脏矩形列表。
246    #[inline]
247    pub fn committed_damage(&self) -> &[Region] {
248        &self.wl_surface.committed_damage
249    }
250}
251
252impl PlatformSurface for WaylandPlatform {
253    #[inline(always)]
254    fn surface_size(&self) -> (i16, i16) {
255        (self.width as i16, self.height as i16)
256    }
257
258    fn flush_frame_dt(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> FlushReport {
259        if self.is_connected_to_compositor() && self.shm_driver.slots.iter().all(|s| s.in_use) {
260            return FlushReport::default();
261        }
262        let prev_buf = self.wl_surface.attached_buffer_id;
263        if self
264            .shm_driver
265            .flush_frame_dt(engine, &mut self.wl_surface, dt_ms)
266        {
267            let active_slot = self.shm_driver.active_slot_idx;
268            let dmg = self.wl_surface.committed_damage.clone();
269
270            #[cfg(unix)]
271            if let Some(conn) = &mut self.compositor_conn {
272                conn.commit_slot_damage(
273                    active_slot,
274                    &self.shm_driver.slots[active_slot].pixels,
275                    &self.shm_driver.last_raster_regions,
276                    &dmg,
277                    &mut self.wire_state,
278                );
279            } else {
280                if let Some(old_id) = prev_buf {
281                    self.shm_driver.release_buffer(old_id);
282                }
283                if self.wire_state.outbound_tx.len() > 4096 {
284                    self.wire_state.outbound_tx.clear();
285                }
286                self.wire_state
287                    .encode_surface_commit_damage(active_slot, &dmg);
288            }
289
290            #[cfg(not(unix))]
291            {
292                if let Some(old_id) = prev_buf {
293                    self.shm_driver.release_buffer(old_id);
294                }
295                if self.wire_state.outbound_tx.len() > 4096 {
296                    self.wire_state.outbound_tx.clear();
297                }
298                self.wire_state
299                    .encode_surface_commit_damage(active_slot, &dmg);
300            }
301
302            let px: usize = dmg
303                .iter()
304                .map(|r| (r.w.max(0) as usize) * (r.h.max(0) as usize))
305                .sum();
306            FlushReport {
307                dirty_regions: dmg.len(),
308                strips_or_buffers: 1,
309                pixels_updated: px,
310            }
311        } else {
312            FlushReport::default()
313        }
314    }
315}
316
317impl Platform for WaylandPlatform {
318    #[inline]
319    fn duration_since_start(&self) -> Duration {
320        self.start_instant.elapsed()
321    }
322
323    fn step_platform(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> PlatformControlFlow {
324        #[cfg(unix)]
325        if let Some(conn) = &mut self.compositor_conn {
326            let evs = conn.poll_wire(&mut self.wire_state);
327            self.process_wire_events(engine, evs);
328        }
329        if self.close_requested {
330            return PlatformControlFlow::Exit;
331        }
332        let report = self.flush_frame_dt(engine, dt_ms);
333        if report.has_updates() || engine.needs_redraw() {
334            PlatformControlFlow::Poll
335        } else {
336            PlatformControlFlow::Wait
337        }
338    }
339}