velox_engine/platform/winit/
mod.rs1#[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
28pub type DesktopWindowRunner = WinitPlatform;
30
31pub 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 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 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 #[inline]
72 pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
73 self.driver.set_backend(backend);
74 self
75 }
76
77 #[inline]
79 pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
80 self.driver.set_backend(backend);
81 }
82
83 #[inline]
85 pub const fn backend(&self) -> super::DesktopRenderBackend {
86 self.driver.backend()
87 }
88
89 #[inline]
91 pub const fn driver(&self) -> &SoftwareSurfaceDriver {
92 &self.driver
93 }
94
95 pub fn run(self, mut core: VeloxEngine, scroll_list_id: Option<u32>) {
97 #[cfg(feature = "winit")]
98 {
99 #[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 #[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 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 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 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