Skip to main content

velox_engine/platform/winit/
mod.rs

1//! 跨平台桌面窗口与事件驱动平台后端 `velox_engine::platform::winit`(Windows / macOS / Linux Wayland)。
2//!
3//! 模块职责划分:
4//! - `mod`:[`WinitPlatform`](及兼容别名 [`DesktopWindowRunner`])对外构建器与 [`Platform`] / [`PlatformSurface`] 实现;
5//! - `handler`:`WinitAppHandler` 原生事件循环、GPU/软光栅桥接、分数 DPI 与 IME 光标跟随;
6//! - `nested`:[`run_nested_compositor_window`] 自定义合成器嵌套窗口宿主。
7
8#[cfg(feature = "winit")]
9mod handler;
10mod nested;
11
12use std::eprintln;
13use std::string::String;
14use std::time::{Duration, Instant};
15
16#[cfg(feature = "winit")]
17use winit::event_loop::EventLoop;
18
19#[cfg(feature = "winit")]
20use handler::{WinitAppHandler, WinitUserEvent};
21pub use nested::run_nested_compositor_window;
22pub use super::shm_driver::{
23    write_uncompressed_png, ShmSlot, ShmSurfaceDriver, SoftwareSurfaceDriver, WaylandSurfaceDriver,
24    WlBuffer, WlSurface,
25};
26use crate::prelude::*;
27
28/// 桌面窗口运行器兼容别名。
29pub type DesktopWindowRunner = WinitPlatform;
30
31/// 基于 `winit` + `softbuffer` 的跨平台桌面窗口平台(支持 Linux Wayland、Windows、macOS)。
32///
33/// 实现 [`Platform`] 与 [`PlatformSurface`] 特征。
34pub struct WinitPlatform {
35    title: String,
36    width: usize,
37    height: usize,
38    dpi_scale: usize,
39    dpi_scale_explicit: bool,
40    start_instant: Instant,
41    driver: SoftwareSurfaceDriver,
42    wl_surface: WlSurface,
43}
44
45impl WinitPlatform {
46    /// 创建指定标题与逻辑尺寸 `(width, height)` 的跨平台 `WinitPlatform` 窗口运行器。
47    pub fn new(title: impl Into<String>, width: usize, height: usize) -> Self {
48        let dpi_scale = 2;
49        Self {
50            title: title.into(),
51            width,
52            height,
53            dpi_scale,
54            dpi_scale_explicit: false,
55            start_instant: Instant::now(),
56            driver: SoftwareSurfaceDriver::new(width * dpi_scale, height * dpi_scale),
57            wl_surface: WlSurface::new(),
58        }
59    }
60
61    /// 设置 HiDPI 缩放倍数(`1` 为原始像素,`2` 为 2× 高清矢量光栅化)。
62    pub fn with_dpi_scale(mut self, scale: usize) -> Self {
63        self.dpi_scale = scale.max(1);
64        self.dpi_scale_explicit = true;
65        self.driver
66            .resize(self.width * self.dpi_scale, self.height * self.dpi_scale);
67        self
68    }
69
70    /// 配置桌面渲染后端类型(默认采用 [`super::DesktopRenderBackend::default_desktop`],即优先 `Wgpu` 2D SDF GPU 后端)。
71    #[inline]
72    pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
73        self.driver.set_backend(backend);
74        self
75    }
76
77    /// 动态切换桌面渲染后端类型。
78    #[inline]
79    pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
80        self.driver.set_backend(backend);
81    }
82
83    /// 返回当前激活的桌面渲染后端类型。
84    #[inline]
85    pub const fn backend(&self) -> super::DesktopRenderBackend {
86        self.driver.backend()
87    }
88
89    /// 返回内部表面驱动器只读引用(用于检查单槽原位复用与局部光栅化脏矩形)。
90    #[inline]
91    pub const fn driver(&self) -> &SoftwareSurfaceDriver {
92        &self.driver
93    }
94
95    /// 启动基于 `winit::event_loop::EventLoop` + `softbuffer` 的原生跨平台窗口事件循环。
96    pub fn run(self, mut core: VeloxEngine, scroll_list_id: Option<u32>) {
97        #[cfg(feature = "winit")]
98        {
99            // 启动阶段后台线程并行预热系统主字体(CJK 语言下同步预热回退字库),与 EventLoop 及 GPU 管线初始化并发重叠
100            #[cfg(not(target_arch = "wasm32"))]
101            {
102                let loc = core.locale();
103                let lang = loc.language();
104                let preload_cjk = lang == "zh" || lang == "ja" || lang == "ko";
105                crate::display::ttf_atlas::spawn_font_preload(preload_cjk);
106            }
107
108            let event_loop = match EventLoop::<WinitUserEvent>::with_user_event().build() {
109                Ok(el) => el,
110                Err(e) => {
111                    eprintln!("[velox::platform::winit] 无法初始化显示服务器 EventLoop ({e}),回退至无头验证模式。");
112                    self.run_headless(&mut core, 10);
113                    return;
114                }
115            };
116            event_loop.listen_device_events(winit::event_loop::DeviceEvents::Never);
117
118            let Self {
119                title,
120                width,
121                height,
122                dpi_scale,
123                dpi_scale_explicit,
124                mut driver,
125                wl_surface,
126                ..
127            } = self;
128
129            let scale_factor = (dpi_scale.max(1)) as f32;
130            core.set_scale_factor(scale_factor);
131            core.set_pointer_kind(PointerKind::Mouse);
132            let async_proxy = event_loop.create_proxy();
133            core.set_async_waker(move || {
134                let _ = async_proxy.send_event(WinitUserEvent::WakeAsync);
135            });
136            let phys_w = ((width as f32) * scale_factor).round().max(1.0) as usize;
137            let phys_h = ((height as f32) * scale_factor).round().max(1.0) as usize;
138
139            // Instant First-Paint + Async GPU Promotion:
140            // 当选用 GPU 后端时,立刻在独立后台线程并发初始化 wgpu 驱动/适配器/设备/着色器管线,
141            // 主线程零阻塞以内置软件光栅器 ~60ms 秒开首屏,后台 GPU 就绪后自动热升舱接管并释放软件双缓冲。
142            #[cfg(feature = "gpu")]
143            let gpu_warmup_in_flight = if driver.backend().is_gpu() {
144                let proxy = event_loop.create_proxy();
145                std::thread::Builder::new()
146                    .name(String::from("velox-gpu-warmup"))
147                    .stack_size(512 * 1024)
148                    .spawn(move || {
149                        let prepared = crate::renderers::wgpu::PreparedWgpuContext::init_headless();
150                        let _ = proxy.send_event(WinitUserEvent::GpuReady(prepared));
151                    })
152                    .is_ok()
153            } else {
154                false
155            };
156
157            // 首帧立即由软件渲染器承接,按真实物理尺寸在 `resumed()` 中分配;GPU 热升舱完成后立即收缩回 1x1 释放内存
158            driver.resize(1, 1);
159
160            let mut app = WinitAppHandler {
161                title,
162                logical_w: width,
163                logical_h: height,
164                phys_w,
165                phys_h,
166                scale_factor,
167                dpi_scale_explicit,
168                core,
169                scroll_list_id,
170                driver,
171                wl_surface,
172                #[cfg(feature = "gpu")]
173                gpu_surface: None,
174                #[cfg(feature = "gpu")]
175                pending_gpu: None,
176                #[cfg(feature = "gpu")]
177                gpu_warmup_in_flight,
178                surface: None,
179                window: None,
180                window_shown: false,
181                force_present_once: false,
182                last_window_theme_dark: None,
183                cursor_pos: (0, 0),
184                mouse_down: false,
185                last_tick: Instant::now() - Duration::from_secs(1),
186                last_ime_area: None,
187                last_cursor: CursorShape::Default,
188            };
189
190            let _ = event_loop.run_app(&mut app);
191        }
192        #[cfg(not(feature = "winit"))]
193        {
194            let _ = scroll_list_id;
195            let _ = &self.title;
196            eprintln!("[velox::platform::winit] 未启用 winit 特性,以无头模式步进 10 帧。");
197            self.run_headless(&mut core, 10);
198        }
199    }
200
201    /// 无头模式运行指定帧数(用于 CI 或无显示服务器环境验证)。
202    pub fn run_headless(&self, core: &mut VeloxEngine, frames: usize) {
203        let scale = self.dpi_scale.max(1);
204        core.set_dpi_scale(scale as i16);
205        let mut driver = SoftwareSurfaceDriver::new(self.width * scale, self.height * scale)
206            .with_backend(self.driver.backend());
207        let mut wl_surface = WlSurface::new();
208        for _ in 0..frames {
209            if let Some(id) = wl_surface.attached_buffer_id {
210                driver.release_buffer(id);
211            }
212            let _ = driver.flush_frame_dt(core, &mut wl_surface, 16);
213        }
214    }
215
216    /// 渲染一帧并将前台 `Xrgb8888` 像素缓冲保存为无损 PNG 图像文件。
217    pub fn render_to_png(&self, core: &mut VeloxEngine, path: &str) -> std::io::Result<()> {
218        let scale = self.dpi_scale.max(1);
219        core.set_dpi_scale(scale as i16);
220        let phys_w = self.width * scale;
221        let phys_h = self.height * scale;
222        let mut driver =
223            SoftwareSurfaceDriver::new(phys_w, phys_h).with_backend(self.driver.backend());
224        let mut wl_surface = WlSurface::new();
225        driver.flush_frame_dt(core, &mut wl_surface, 16);
226        write_uncompressed_png(path, phys_w, phys_h, driver.front_pixels())
227    }
228}
229
230
231impl PlatformSurface for WinitPlatform {
232    #[inline(always)]
233    fn surface_size(&self) -> (i16, i16) {
234        (self.width as i16, self.height as i16)
235    }
236
237    fn flush_frame_dt(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> FlushReport {
238        engine.set_dpi_scale(self.dpi_scale.max(1) as i16);
239        if let Some(old_id) = self.wl_surface.attached_buffer_id {
240            self.driver.release_buffer(old_id);
241        }
242        if self
243            .driver
244            .flush_frame_dt(engine, &mut self.wl_surface, dt_ms)
245        {
246            let rects = self.wl_surface.committed_damage.len();
247            let px: usize = self
248                .wl_surface
249                .committed_damage
250                .iter()
251                .map(|r| (r.w.max(0) as usize) * (r.h.max(0) as usize))
252                .sum();
253            FlushReport {
254                dirty_regions: rects,
255                strips_or_buffers: 1,
256                pixels_updated: px,
257            }
258        } else {
259            FlushReport::default()
260        }
261    }
262}
263
264impl Platform for WinitPlatform {
265    #[inline]
266    fn duration_since_start(&self) -> Duration {
267        self.start_instant.elapsed()
268    }
269
270    fn step_platform(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> PlatformControlFlow {
271        let report = self.flush_frame_dt(engine, dt_ms);
272        if report.has_updates() || engine.needs_redraw() {
273            PlatformControlFlow::Poll
274        } else {
275            PlatformControlFlow::Wait
276        }
277    }
278
279    fn run_event_loop(self, engine: VeloxEngine) {
280        self.run(engine, None);
281    }
282}
283