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