euv_core/platform/headless/impl.rs
1use super::*;
2
3/// Default `HeadlessPlatform` at 1.0x scale and Light theme.
4impl Default for HeadlessPlatform {
5 /// Creates a clean offscreen headless platform backend.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Default `HeadlessPlatform`.
10 fn default() -> Self {
11 Self {
12 emulated_kind: PlatformKind::Headless,
13 scale_factor: 1.0,
14 safe_area: SafeAreaInsets::default(),
15 theme: ThemeMode::Light,
16 refresh_rate_hz: FALLBACK_REFRESH_RATE_HZ,
17 next_id: 1,
18 windows: HashMap::new(),
19 pending_events: Vec::new(),
20 clipboard: None,
21 pump_paused: false,
22 wait_calls: 0,
23 capture_last_frame: false,
24 }
25 }
26}
27
28/// Configuration and event injection helpers for `HeadlessPlatform`.
29impl HeadlessPlatform {
30 /// Creates a headless platform emulating a specific target platform's form factor and DPI.
31 ///
32 /// # Arguments
33 ///
34 /// - `PlatformKind` - Target platform to emulate.
35 /// - `f32` - Simulated DPI scale factor.
36 /// - `SafeAreaInsets` - Simulated safe-area insets.
37 ///
38 /// # Returns
39 ///
40 /// - `Self` - Configured headless backend.
41 #[must_use]
42 pub fn emulating(platform: PlatformKind, scale_factor: f32, safe_area: SafeAreaInsets) -> Self {
43 let mut backend: Self = Self::default();
44 backend.set_emulated_kind(platform);
45 backend.set_scale_factor(scale_factor.max(0.5));
46 backend.set_safe_area(safe_area);
47 backend
48 }
49
50 /// Overrides the simulated hardware refresh rate in Hertz for deterministic high-refresh testing.
51 ///
52 /// # Arguments
53 ///
54 /// - `Self` - Headless platform builder.
55 /// - `f32` - Simulated display refresh rate in Hertz (`24.0`..=`480.0`).
56 ///
57 /// # Returns
58 ///
59 /// - `Self` - Updated headless backend.
60 #[must_use]
61 pub fn with_refresh_rate_hz(mut self, hz: f32) -> Self {
62 let pacing: FramePacingConfig = compute_frame_pacing(hz);
63 self.set_refresh_rate_hz(pacing.get_preferred_hz());
64 self
65 }
66
67 /// Enqueues a synthetic `WindowEvent` to be consumed on the next `poll_events()` call.
68 ///
69 /// # Arguments
70 ///
71 /// - `&Self` - Mutable headless platform.
72 /// - `WindowEvent` - Synthetic event to inject.
73 pub fn push_event(&mut self, event: WindowEvent) {
74 self.get_mut_pending_events().push(event);
75 }
76
77 /// Enqueues a synthetic `SystemEvent` wrapped as `WindowEvent::System` for deterministic testing.
78 ///
79 /// # Arguments
80 ///
81 /// - `&Self` - Mutable headless platform.
82 /// - `SystemEvent` - System event to inject.
83 pub fn push_system_event(&mut self, event: SystemEvent) {
84 self.get_mut_pending_events()
85 .push(WindowEvent::System(event));
86 }
87
88 /// Enables or disables per-frame `Framebuffer` snapshot capture (`false` by default to avoid dead multi-MB clones).
89 ///
90 /// # Arguments
91 ///
92 /// - `bool` - `true` to capture each presented framebuffer for pixel inspection; `false` for zero-clone presentation.
93 ///
94 /// # Returns
95 ///
96 /// - `Self` - Updated headless backend.
97 #[must_use]
98 pub fn with_capture_last_frame(mut self, enabled: bool) -> Self {
99 self.set_capture_last_frame(enabled);
100 self
101 }
102
103 /// Returns a reference to the last presented `Framebuffer` for `id` when `capture_last_frame` is enabled.
104 ///
105 /// # Arguments
106 ///
107 /// - `WindowId` - Window identifier.
108 ///
109 /// # Returns
110 ///
111 /// - `Option<&Framebuffer>` - Most recently captured pixel buffer, or `None` when snapshot capture is disabled.
112 #[must_use]
113 pub fn last_framebuffer(&self, id: WindowId) -> Option<&Framebuffer> {
114 if !self.get_capture_last_frame() {
115 return None;
116 }
117 self.get_windows()
118 .get(&id)
119 .map(HeadlessWindowRecord::get_last_frame)
120 }
121}
122
123/// `WindowController` implementation for `HeadlessPlatform`.
124impl WindowController for HeadlessPlatform {
125 /// Applies a `WindowCommand` against the in-memory headless window record.
126 ///
127 /// # Arguments
128 ///
129 /// - `&Self` - Mutable headless platform.
130 /// - `WindowCommand` - Command to apply.
131 ///
132 /// # Returns
133 ///
134 /// - `Result<(), PlatformError>` - Success or `WindowNotFound`.
135 fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
136 match command {
137 WindowCommand::SetTitle(id, title) => {
138 let record: &mut HeadlessWindowRecord = self
139 .get_mut_windows()
140 .get_mut(&id)
141 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
142 record.get_mut_config().set_title(title);
143 Ok(())
144 }
145 WindowCommand::SetSize(id, width, height) => {
146 let scale: f32 = {
147 let record: &mut HeadlessWindowRecord = self
148 .get_mut_windows()
149 .get_mut(&id)
150 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
151 let s: f32 = record.get_state().get_scale_factor();
152 record.get_mut_config().set_width(width.max(1));
153 record.get_mut_config().set_height(height.max(1));
154 record
155 .get_mut_state()
156 .set_logical_width(width.max(1) as f32);
157 record
158 .get_mut_state()
159 .set_logical_height(height.max(1) as f32);
160 record
161 .get_mut_state()
162 .set_physical_width(((width.max(1) as f32) * s).round() as u32);
163 record
164 .get_mut_state()
165 .set_physical_height(((height.max(1) as f32) * s).round() as u32);
166 s
167 };
168 self.push_event(WindowEvent::Resized(id, width.max(1), height.max(1), scale));
169 Ok(())
170 }
171 WindowCommand::SetPosition(id, x, y) => {
172 let record: &mut HeadlessWindowRecord = self
173 .get_mut_windows()
174 .get_mut(&id)
175 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
176 record.get_mut_config().set_position(Some((x, y)));
177 Ok(())
178 }
179 WindowCommand::SetResizable(id, resizable) => {
180 let record: &mut HeadlessWindowRecord = self
181 .get_mut_windows()
182 .get_mut(&id)
183 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
184 record.get_mut_config().set_resizable(resizable);
185 Ok(())
186 }
187 WindowCommand::SetDecorations(id, decorations) => {
188 let record: &mut HeadlessWindowRecord = self
189 .get_mut_windows()
190 .get_mut(&id)
191 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
192 record.get_mut_config().set_decorations(decorations);
193 Ok(())
194 }
195 WindowCommand::SetAlwaysOnTop(id, on_top) => {
196 let record: &mut HeadlessWindowRecord = self
197 .get_mut_windows()
198 .get_mut(&id)
199 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
200 record.get_mut_config().set_always_on_top(on_top);
201 Ok(())
202 }
203 WindowCommand::SetFullscreen(id, mode) => {
204 let record: &mut HeadlessWindowRecord = self
205 .get_mut_windows()
206 .get_mut(&id)
207 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
208 record.get_mut_config().set_fullscreen(mode);
209 record.get_mut_state().set_fullscreen(mode);
210 Ok(())
211 }
212 WindowCommand::SetVisible(id, visible) => {
213 let record: &mut HeadlessWindowRecord = self
214 .get_mut_windows()
215 .get_mut(&id)
216 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
217 record.get_mut_config().set_visible(visible);
218 Ok(())
219 }
220 WindowCommand::SetCursor(id, cursor) => {
221 let record: &mut HeadlessWindowRecord = self
222 .get_mut_windows()
223 .get_mut(&id)
224 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
225 record.set_cursor(cursor);
226 Ok(())
227 }
228 WindowCommand::SetIme(id, enabled, rect) => {
229 let record: &mut HeadlessWindowRecord = self
230 .get_mut_windows()
231 .get_mut(&id)
232 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
233 record.set_ime_active(enabled);
234 record.set_ime_rect(rect);
235 Ok(())
236 }
237 WindowCommand::SetStatusBarStyle(id, style) => {
238 let record: &mut HeadlessWindowRecord = self
239 .get_mut_windows()
240 .get_mut(&id)
241 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
242 record.get_mut_config().set_status_bar(style);
243 Ok(())
244 }
245 WindowCommand::RequestRedraw(id) => {
246 if !self.get_windows().contains_key(&id) {
247 return Err(PlatformError::WindowNotFound(id.get_value()));
248 }
249 self.push_event(WindowEvent::RedrawRequested(id));
250 Ok(())
251 }
252 WindowCommand::SetRenderMode(id, mode) => {
253 let record: &mut HeadlessWindowRecord = self
254 .get_mut_windows()
255 .get_mut(&id)
256 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
257 record.get_mut_config().get_mut_render().set_mode(mode);
258 Ok(())
259 }
260 WindowCommand::Close(id) => {
261 if self.get_mut_windows().remove(&id).is_none() {
262 return Err(PlatformError::WindowNotFound(id.get_value()));
263 }
264 Ok(())
265 }
266 }
267 }
268}
269
270/// `PlatformBackend` implementation for `HeadlessPlatform`.
271impl PlatformBackend for HeadlessPlatform {
272 /// Returns the emulated `PlatformKind`.
273 ///
274 /// # Arguments
275 ///
276 /// - `&Self` - Platform reference.
277 ///
278 /// # Returns
279 ///
280 /// - `PlatformKind` - Emulated platform kind.
281 fn kind(&self) -> PlatformKind {
282 self.get_emulated_kind()
283 }
284
285 /// Returns normalized capabilities for the emulated platform.
286 ///
287 /// # Arguments
288 ///
289 /// - `&Self` - Platform reference.
290 ///
291 /// # Returns
292 ///
293 /// - `PlatformCapabilities` - Capability matrix.
294 fn capabilities(&self) -> PlatformCapabilities {
295 PlatformCapabilities::for_platform(self.get_emulated_kind())
296 }
297
298 /// Allocates an offscreen window record with simulated DPI and safe-area insets.
299 ///
300 /// # Arguments
301 ///
302 /// - `&Self` - Mutable headless platform.
303 /// - `&WindowConfig` - Window configuration.
304 ///
305 /// # Returns
306 ///
307 /// - `Result<WindowState, PlatformError>` - Created window state.
308 fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
309 let id: WindowId = WindowId::new(self.get_next_id());
310 self.set_next_id(self.get_next_id().wrapping_add(1));
311 let mut state: WindowState = WindowState::from_config(id, config, self.get_scale_factor());
312 state.set_safe_area(self.get_safe_area());
313 state.set_system_theme(self.get_theme());
314 state
315 .get_mut_display()
316 .set_refresh_rate_hz(self.get_refresh_rate_hz().round() as u32);
317 let record: HeadlessWindowRecord = HeadlessWindowRecord {
318 config: config.clone(),
319 state,
320 cursor: CursorIcon::Default,
321 last_frame: Framebuffer::allocate(1, 1),
322 present_count: 0,
323 ime_active: false,
324 ime_rect: Rect::default(),
325 };
326 self.get_mut_windows().insert(id, record);
327 Ok(state)
328 }
329
330 /// Queries current `WindowState` for `id`.
331 ///
332 /// # Arguments
333 ///
334 /// - `&Self` - Platform reference.
335 /// - `WindowId` - Window handle.
336 ///
337 /// # Returns
338 ///
339 /// - `Option<WindowState>` - Window state if alive.
340 fn window_state(&self, id: WindowId) -> Option<WindowState> {
341 self.get_windows()
342 .get(&id)
343 .map(HeadlessWindowRecord::get_state)
344 }
345
346 /// Returns `RawWindowHandle::Headless`.
347 ///
348 /// # Arguments
349 ///
350 /// - `&Self` - Platform reference.
351 /// - `WindowId` - Window handle.
352 ///
353 /// # Returns
354 ///
355 /// - `RawWindowHandle` - Headless handle.
356 fn raw_window_handle(&self, _id: WindowId) -> RawWindowHandle {
357 RawWindowHandle::Headless
358 }
359
360 /// Drains injected synthetic events.
361 ///
362 /// # Arguments
363 ///
364 /// - `&Self` - Mutable headless platform.
365 ///
366 /// # Returns
367 ///
368 /// - `Vec<WindowEvent>` - Pending events.
369 fn poll_events(&mut self) -> Vec<WindowEvent> {
370 take(self.get_mut_pending_events())
371 }
372
373 /// Records a background wait invocation and drains any queued synthetic events immediately.
374 ///
375 /// # Arguments
376 ///
377 /// - `&Self` - Mutable headless platform.
378 ///
379 /// # Returns
380 ///
381 /// - `Vec<WindowEvent>` - Pending events.
382 fn wait_for_events(&mut self) -> Vec<WindowEvent> {
383 let next_calls: u64 = self.get_wait_calls().saturating_add(1);
384 self.set_wait_calls(next_calls);
385 self.poll_events()
386 }
387
388 /// Updates headless frame pump pause state for deterministic background freeze testing.
389 ///
390 /// # Arguments
391 ///
392 /// - `&Self` - Mutable headless platform.
393 /// - `bool` - `true` when paused in background; `false` when active.
394 fn set_frame_pump_paused(&mut self, paused: bool) {
395 self.set_pump_paused(paused);
396 }
397
398 /// Returns whether the headless frame pump is currently paused.
399 ///
400 /// # Arguments
401 ///
402 /// - `&Self` - Platform reference.
403 ///
404 /// # Returns
405 ///
406 /// - `bool` - `true` when paused in background.
407 fn is_frame_pump_paused(&self) -> bool {
408 self.get_pump_paused()
409 }
410
411 /// Stores a copy of `framebuffer` inside the headless window record for pixel inspection.
412 ///
413 /// # Arguments
414 ///
415 /// - `&Self` - Mutable headless platform.
416 /// - `WindowId` - Target window handle.
417 /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
418 ///
419 /// # Returns
420 ///
421 /// - `Result<(), PlatformError>` - Presentation status.
422 fn present_framebuffer(
423 &mut self,
424 id: WindowId,
425 framebuffer: &Framebuffer,
426 ) -> Result<(), PlatformError> {
427 let capture: bool = self.get_capture_last_frame();
428 let record: &mut HeadlessWindowRecord = self
429 .get_mut_windows()
430 .get_mut(&id)
431 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
432 if capture {
433 record.set_last_frame(framebuffer.clone());
434 }
435 record.set_present_count(record.get_present_count().wrapping_add(1));
436 Ok(())
437 }
438
439 /// Reads the simulated clipboard string.
440 ///
441 /// # Arguments
442 ///
443 /// - `&Self` - Platform reference.
444 ///
445 /// # Returns
446 ///
447 /// - `Option<String>` - Stored clipboard contents.
448 fn read_clipboard(&self) -> Option<String> {
449 let Self { clipboard, .. } = self;
450 clipboard.clone()
451 }
452
453 /// Writes `text` into the simulated clipboard.
454 ///
455 /// # Arguments
456 ///
457 /// - `&Self` - Mutable platform.
458 /// - `&str` - Clipboard text.
459 ///
460 /// # Returns
461 ///
462 /// - `Result<(), PlatformError>` - Always succeeds.
463 fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
464 self.set_clipboard(Some(text.to_string()));
465 let _: bool = dispatch_native_action(NATIVE_ACTION_CLIPBOARD, CLIPBOARD_ACTION_WRITE, text);
466 Ok(())
467 }
468
469 /// Returns the simulated OS theme mode.
470 ///
471 /// # Arguments
472 ///
473 /// - `&Self` - Platform reference.
474 ///
475 /// # Returns
476 ///
477 /// - `ThemeMode` - Simulated theme mode.
478 fn system_theme(&self) -> ThemeMode {
479 self.get_theme()
480 }
481
482 /// Returns the simulated display refresh rate in Hertz.
483 ///
484 /// # Arguments
485 ///
486 /// - `&Self` - Platform reference.
487 ///
488 /// # Returns
489 ///
490 /// - `f32` - Simulated refresh rate in Hertz.
491 fn display_refresh_rate_hz(&self) -> f32 {
492 self.get_refresh_rate_hz()
493 }
494}