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