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