Skip to main content

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