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, 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
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 app = std::boxed::Box::new(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 #[cfg(feature = "gpu")]
184 pending_gpu_damage: std::vec::Vec::new(),
185 #[cfg(feature = "gpu")]
186 pending_gpu_full_repaint: false,
187 #[cfg(feature = "gpu")]
188 gpu_present_retry_streak: 0,
189 #[cfg(feature = "gpu")]
190 gpu_retry_not_before: None,
191 #[cfg(feature = "gpu")]
192 window_occluded: false,
193 surface: None,
194 window: None,
195 window_shown: false,
196 force_present_once: false,
197 last_window_theme_dark: None,
198 cursor_pos: (0, 0),
199 mouse_down: false,
200 last_tick: Instant::now() - Duration::from_secs(1),
201 last_ime_area: None,
202 last_cursor: CursorShape::Default,
203 });
204
205 run_winit_event_loop(event_loop, app);
206 }
207 #[cfg(not(feature = "winit"))]
208 {
209 let _ = scroll_list_id;
210 let _ = &self.title;
211 eprintln!("[velox::platform::winit] 未启用 winit 特性,以无头模式步进 10 帧。");
212 self.run_headless(&mut core, 10);
213 }
214 }
215
216 pub fn run_headless(&self, core: &mut VeloxEngine, frames: usize) {
218 let scale = self.dpi_scale.max(1);
219 core.set_dpi_scale(scale as i16);
220 let mut driver = SoftwareSurfaceDriver::new(self.width * scale, self.height * scale)
221 .with_backend(self.driver.backend());
222 let mut wl_surface = WlSurface::new();
223 for _ in 0..frames {
224 if let Some(id) = wl_surface.attached_buffer_id {
225 driver.release_buffer(id);
226 }
227 let _ = driver.flush_frame_dt(core, &mut wl_surface, 16);
228 }
229 }
230
231 pub fn render_to_png(&self, core: &mut VeloxEngine, path: &str) -> std::io::Result<()> {
233 let scale = self.dpi_scale.max(1);
234 core.set_dpi_scale(scale as i16);
235 core.force_full_repaint();
237 let phys_w = self.width * scale;
238 let phys_h = self.height * scale;
239 let mut driver =
240 SoftwareSurfaceDriver::new(phys_w, phys_h).with_backend(self.driver.backend());
241 let mut wl_surface = WlSurface::new();
242 driver.flush_frame_dt(core, &mut wl_surface, 16);
243 write_uncompressed_png(path, phys_w, phys_h, driver.front_pixels())
244 }
245}
246
247
248#[cfg(feature = "winit")]
249#[inline(never)]
250fn run_winit_event_loop(
251 event_loop: EventLoop<WinitUserEvent>,
252 mut app: std::boxed::Box<WinitAppHandler>,
253) {
254 let _ = event_loop.run_app(&mut *app);
255}
256
257impl PlatformSurface for WinitPlatform {
258 #[inline(always)]
259 fn surface_size(&self) -> (i16, i16) {
260 (self.width as i16, self.height as i16)
261 }
262
263 fn flush_frame_dt(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> FlushReport {
264 engine.set_dpi_scale(self.dpi_scale.max(1) as i16);
265 if let Some(old_id) = self.wl_surface.attached_buffer_id {
266 self.driver.release_buffer(old_id);
267 }
268 if self
269 .driver
270 .flush_frame_dt(engine, &mut self.wl_surface, dt_ms)
271 {
272 let rects = self.wl_surface.committed_damage.len();
273 let px: usize = self
274 .wl_surface
275 .committed_damage
276 .iter()
277 .map(|r| (r.w.max(0) as usize) * (r.h.max(0) as usize))
278 .sum();
279 FlushReport::with_engine(rects, 1, px, engine)
280 } else {
281 FlushReport::default()
282 }
283 }
284}
285
286impl Platform for WinitPlatform {
287 #[inline]
288 fn duration_since_start(&self) -> Duration {
289 self.start_instant.elapsed()
290 }
291
292 fn step_platform(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> PlatformControlFlow {
293 let report = self.flush_frame_dt(engine, dt_ms);
294 if report.has_updates() || engine.needs_redraw() {
295 PlatformControlFlow::Poll
296 } else {
297 PlatformControlFlow::Wait
298 }
299 }
300
301 fn run_event_loop(self, engine: VeloxEngine) {
302 self.run(engine, None);
303 }
304}
305