Skip to main content

strata/runtime/
app.rs

1//! High-level declarative application entry point and builder.
2
3use super::*;
4
5pub fn app() -> StrataAppBuilder {
6    StrataApp::builder()
7}
8/// Outcome returned by a periodic application frame callback.
9///
10/// Returning [`FrameOutcome::Dirty`] marks the runtime dirty so the root view
11/// function is re-invoked and the window is repainted. Returning
12/// [`FrameOutcome::Unchanged`] skips rebuild, layout, compile, and paint.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum FrameOutcome {
15    #[default]
16    Unchanged,
17    Dirty,
18}
19
20impl FrameOutcome {
21    /// Returns `true` when the callback modified application state and needs a redraw.
22    pub fn is_dirty(self) -> bool {
23        matches!(self, Self::Dirty)
24    }
25}
26
27/// Frame timing and metrics information passed to frame lifecycle callbacks.
28#[derive(Debug, Clone, Copy, PartialEq, Default)]
29pub struct AppFrameInfo {
30    pub frame_index: u64,
31    pub viewport_width: f32,
32    pub viewport_height: f32,
33    pub dpr: f32,
34    pub command_count: usize,
35    pub dt: std::time::Duration,
36}
37
38/// Low-level lifecycle callbacks.
39#[derive(Default)]
40pub struct AppLifecycleHooks {
41    pub on_start: Option<Box<dyn FnMut(&mut AppRuntime)>>,
42    pub on_event: Option<Box<dyn FnMut(&PlatformEvent, &mut EventLoopControl, &mut AppRuntime)>>,
43    pub on_frame: Option<Box<dyn FnMut(AppFrameInfo, &mut AppRuntime)>>,
44    pub on_draw: Option<Box<dyn FnMut(&mut DisplayList)>>,
45    pub on_exit: Option<Box<dyn FnMut(&mut AppRuntime)>>,
46}
47
48/// Low-level application orchestrator with fine-grained control over windowing, swapchain presentation,
49/// lifecycle hooks, and manual frame pacing.
50pub struct StrataApp {
51    pub runtime: AppRuntime,
52    pub window_config: WindowConfig,
53    pub hooks: AppLifecycleHooks,
54    pub compositor: SwapchainCompositor,
55    pub presenter: SoftwareSurfacePresenter,
56}
57
58impl StrataApp {
59    /// Creates a fluent low-level builder for configuring and launching a Strata app.
60    pub fn builder() -> StrataAppBuilder {
61        StrataAppBuilder::new()
62    }
63
64    /// Advances the runtime by a single frame and returns the generated display commands.
65    pub fn step_frame(&mut self) -> &DisplayList {
66        self.runtime.tick_frame();
67        if let Some(ref mut on_draw) = self.hooks.on_draw {
68            on_draw(&mut self.runtime.display_list);
69        }
70        &self.runtime.display_list
71    }
72
73    /// Dispatches a platform event into the runtime and lifecycle hooks.
74    pub fn dispatch_event(&mut self, event: &PlatformEvent) -> bool {
75        let mut control = EventLoopControl::Poll;
76        if let Some(ref mut on_event) = self.hooks.on_event {
77            on_event(event, &mut control, &mut self.runtime);
78        }
79        self.runtime.step_event(event)
80    }
81
82    /// Renders current frame to internal software surface buffer and returns immutable slice of BGRA pixels.
83    pub fn render_to_buffer(&mut self) -> Result<&[u8], PresentError> {
84        self.step_frame();
85        self.compositor.render_and_present(
86            &self.runtime.display_list,
87            &mut self.presenter,
88            true,
89        )?;
90        Ok(&self.presenter.backing_buffer)
91    }
92
93    /// Runs the application headlessly for a specified number of frames.
94    pub fn run_headless(&mut self, frame_count: u64) -> Vec<AppFrameInfo> {
95        if let Some(ref mut on_start) = self.hooks.on_start {
96            on_start(&mut self.runtime);
97        }
98        let mut metrics = Vec::with_capacity(frame_count as usize);
99        for _ in 0..frame_count {
100            self.step_frame();
101            let info = AppFrameInfo {
102                frame_index: self.runtime.frame_count,
103                viewport_width: self.runtime.viewport_width,
104                viewport_height: self.runtime.viewport_height,
105                dpr: self.runtime.dpr,
106                command_count: self.runtime.display_list.commands.len(),
107                dt: std::time::Duration::ZERO,
108            };
109            if let Some(ref mut on_frame) = self.hooks.on_frame {
110                on_frame(info, &mut self.runtime);
111            }
112            metrics.push(info);
113        }
114        if let Some(ref mut on_exit) = self.hooks.on_exit {
115            on_exit(&mut self.runtime);
116        }
117        metrics
118    }
119
120    /// Runs the platform window event loop with surface presentation.
121    pub fn run_with_event_loop<E: EventLoop>(mut self, event_loop: &mut E) {
122        println!(
123            "[+] Launching Strata Native App: \"{}\"...",
124            self.window_config.title
125        );
126        let mut window = LivePlatformWindow::new(self.window_config.clone());
127
128        if let Some(ref mut on_start) = self.hooks.on_start {
129            on_start(&mut self.runtime);
130        }
131
132        let _ = self
133            .runtime
134            .render_frame(&mut self.compositor, &mut self.presenter, true);
135
136        let hooks = &mut self.hooks;
137        let runtime = &mut self.runtime;
138        let compositor = &mut self.compositor;
139        let presenter = &mut self.presenter;
140
141        event_loop.run(|event, control| {
142            if let Some(ref mut on_event) = hooks.on_event {
143                on_event(&event, control, runtime);
144            }
145
146            match event {
147                PlatformEvent::WindowResized { width, height } => {
148                    compositor.resize(width, height, runtime.dpr);
149                    let _ = presenter.resize(width, height);
150                }
151                PlatformEvent::ScaleFactorChanged { scale_factor } => {
152                    compositor.resize(
153                        runtime.viewport_width as u32,
154                        runtime.viewport_height as u32,
155                        scale_factor,
156                    );
157                }
158                PlatformEvent::WindowCloseRequested => {
159                    *control = EventLoopControl::Exit;
160                    return;
161                }
162                _ => {}
163            }
164
165            let needs_redraw = runtime.step_event(&event);
166
167            if needs_redraw || window.is_redraw_requested() {
168                if let Some(ref mut on_draw) = hooks.on_draw {
169                    on_draw(&mut runtime.display_list);
170                }
171                let _ = runtime.render_frame(compositor, presenter, false);
172                let _ = window.present_surface(
173                    &presenter.backing_buffer,
174                    presenter.width,
175                    presenter.height,
176                );
177                if let Some(ref mut on_frame) = hooks.on_frame {
178                    let info = AppFrameInfo {
179                        frame_index: runtime.frame_count,
180                        viewport_width: runtime.viewport_width,
181                        viewport_height: runtime.viewport_height,
182                        dpr: runtime.dpr,
183                        command_count: runtime.display_list.commands.len(),
184                        dt: std::time::Duration::ZERO,
185                    };
186                    on_frame(info, runtime);
187                }
188            }
189
190            *control = EventLoopControl::Wait;
191        });
192
193        if let Some(ref mut on_exit) = self.hooks.on_exit {
194            on_exit(&mut self.runtime);
195        }
196    }
197
198    /// Runs the application using the native platform window (Wayland/X11 on Linux,
199    /// Win32 on Windows, Cocoa on macOS), or headless fallback when running headless.
200    pub fn run(mut self) {
201        if std::env::var("STRATA_HEADLESS").is_ok() {
202            let window = strata_platform::MockPlatformWindow::new(self.window_config.clone());
203            let _ = crate::runtime::platforms::run_native_surface_window_loop(
204                window,
205                None::<fn() -> View>,
206                self.runtime,
207                self.compositor,
208                self.presenter,
209                |_, _| false,
210                Some(&mut self.hooks),
211            );
212            return;
213        }
214
215        #[cfg(target_os = "linux")]
216        {
217            if std::env::var("WAYLAND_DISPLAY").is_ok() {
218                if let Ok(window) = strata_platform::WaylandWindow::new(self.window_config.clone())
219                {
220                    let _ = crate::runtime::platforms::run_native_surface_window_loop(
221                        window,
222                        None::<fn() -> View>,
223                        self.runtime,
224                        self.compositor,
225                        self.presenter,
226                        |_, _| false,
227                        Some(&mut self.hooks),
228                    );
229                    return;
230                }
231            }
232            if std::env::var("DISPLAY").is_ok() {
233                if let Ok(window) = strata_platform::X11Window::new(self.window_config.clone()) {
234                    let _ = crate::runtime::platforms::run_native_surface_window_loop(
235                        window,
236                        None::<fn() -> View>,
237                        self.runtime,
238                        self.compositor,
239                        self.presenter,
240                        |_, _| false,
241                        Some(&mut self.hooks),
242                    );
243                    return;
244                }
245            }
246        }
247        #[cfg(windows)]
248        {
249            if let Ok(window) = strata_platform::Win32Window::new(self.window_config.clone()) {
250                let _ = crate::runtime::platforms::run_native_surface_window_loop(
251                    window,
252                    None::<fn() -> View>,
253                    self.runtime,
254                    self.compositor,
255                    self.presenter,
256                    |_, _| false,
257                    Some(&mut self.hooks),
258                );
259                return;
260            }
261        }
262        #[cfg(target_os = "macos")]
263        {
264            if let Ok(window) = strata_platform::MacOsWindow::new(self.window_config.clone()) {
265                let _ = crate::runtime::platforms::run_native_surface_window_loop(
266                    window,
267                    None::<fn() -> View>,
268                    self.runtime,
269                    self.compositor,
270                    self.presenter,
271                    |_, _| false,
272                    Some(&mut self.hooks),
273                );
274                return;
275            }
276        }
277        let window = strata_platform::LivePlatformWindow::new(self.window_config.clone());
278        let _ = crate::runtime::platforms::run_native_surface_window_loop(
279            window,
280            None::<fn() -> View>,
281            self.runtime,
282            self.compositor,
283            self.presenter,
284            |_, _| false,
285            Some(&mut self.hooks),
286        );
287    }
288}
289
290/// Fluent builder for low-level application configuration and initialization.
291pub struct StrataAppBuilder {
292    window_config: WindowConfig,
293    dpr: f32,
294    hooks: AppLifecycleHooks,
295}
296
297impl Default for StrataAppBuilder {
298    fn default() -> Self {
299        Self::new()
300    }
301}
302
303impl StrataAppBuilder {
304    pub fn new() -> Self {
305        Self {
306            window_config: WindowConfig::default(),
307            dpr: 1.0,
308            hooks: AppLifecycleHooks::default(),
309        }
310    }
311
312    pub fn with_window(mut self, config: WindowConfig) -> Self {
313        self.window_config = config;
314        self
315    }
316
317    pub fn with_dpr(mut self, dpr: f32) -> Self {
318        self.dpr = dpr;
319        self
320    }
321
322    /// Configures the pointer dwell delay before native hover tooltips (`title` / `alt`) appear.
323    pub fn with_tooltip_delay(mut self, delay: std::time::Duration) -> Self {
324        self.window_config.tooltip_delay = delay;
325        self
326    }
327
328    /// Configures the pointer dwell delay in milliseconds before native hover tooltips appear.
329    pub fn with_tooltip_delay_ms(mut self, delay_ms: u64) -> Self {
330        self.window_config.tooltip_delay = std::time::Duration::from_millis(delay_ms);
331        self
332    }
333
334    /// Configures visual styling and offset for native hover tooltips.
335    pub fn with_tooltip_style(mut self, style: strata_platform::HoverTooltipStyle) -> Self {
336        self.window_config.tooltip_style = style;
337        self
338    }
339
340    pub fn on_start<F: FnMut(&mut AppRuntime) + 'static>(mut self, cb: F) -> Self {
341        self.hooks.on_start = Some(Box::new(cb));
342        self
343    }
344
345    pub fn on_event<F: FnMut(&PlatformEvent, &mut EventLoopControl, &mut AppRuntime) + 'static>(
346        mut self,
347        cb: F,
348    ) -> Self {
349        self.hooks.on_event = Some(Box::new(cb));
350        self
351    }
352
353    pub fn on_frame<F: FnMut(AppFrameInfo, &mut AppRuntime) + 'static>(mut self, cb: F) -> Self {
354        self.hooks.on_frame = Some(Box::new(cb));
355        self
356    }
357
358    pub fn on_draw<F: FnMut(&mut DisplayList) + 'static>(mut self, cb: F) -> Self {
359        self.hooks.on_draw = Some(Box::new(cb));
360        self
361    }
362
363    pub fn on_exit<F: FnMut(&mut AppRuntime) + 'static>(mut self, cb: F) -> Self {
364        self.hooks.on_exit = Some(Box::new(cb));
365        self
366    }
367
368    pub fn build<F: FnOnce() -> View>(self, root: F) -> StrataApp {
369        let view = root();
370        let width = self.window_config.width as f32;
371        let height = self.window_config.height as f32;
372        let mut runtime = AppRuntime::new(view, width, height, self.dpr);
373        runtime.apply_window_config(&self.window_config);
374        let presenter = SoftwareSurfacePresenter::new(
375            self.window_config.width,
376            self.window_config.height,
377            SwapchainFormat::Bgra8Unorm,
378        );
379        let compositor = SwapchainCompositor::new(
380            self.window_config.width,
381            self.window_config.height,
382            self.dpr,
383        );
384
385        StrataApp {
386            runtime,
387            window_config: self.window_config,
388            hooks: self.hooks,
389            compositor,
390            presenter,
391        }
392    }
393}