velox_engine/platform/winit/
mod.rs1#[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, MultiWindowId, MultiWindowManager, MultiWindowSpec, WindowRole,
24 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
33pub type DesktopWindowRunner = WinitPlatform;
35
36pub 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 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 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 #[inline]
77 pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
78 self.driver.set_backend(backend);
79 self
80 }
81
82 #[inline]
84 pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
85 self.driver.set_backend(backend);
86 }
87
88 #[inline]
90 pub const fn backend(&self) -> super::DesktopRenderBackend {
91 self.driver.backend()
92 }
93
94 #[inline]
96 pub const fn driver(&self) -> &SoftwareSurfaceDriver {
97 &self.driver
98 }
99
100 pub fn run(self, mut core: VeloxEngine, scroll_list_id: Option<u32>) {
102 #[cfg(feature = "winit")]
103 {
104 #[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 #[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 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 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 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 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