strata-ui 0.1.5

Universal frontend framework in pure Rust with pixel-perfect CSS emulation and React/TSX ergonomics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! High-level declarative application entry point and builder.

use super::*;

pub fn app() -> StrataAppBuilder {
    StrataApp::builder()
}
/// Outcome returned by a periodic application frame callback.
///
/// Returning [`FrameOutcome::Dirty`] marks the runtime dirty so the root view
/// function is re-invoked and the window is repainted. Returning
/// [`FrameOutcome::Unchanged`] skips rebuild, layout, compile, and paint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FrameOutcome {
    #[default]
    Unchanged,
    /// Re-invokes the root view closure, relayouts, and repaints the full frame.
    Dirty,
    /// Marks retained `Canvas3D` viewports dirty so 3D scenes repaint without
    /// rebuilding the DOM tree or UI layout caches.
    RepaintCanvas3D,
}

impl FrameOutcome {
    /// Returns `true` when the callback modified application state and needs a full UI rebuild.
    pub fn is_dirty(self) -> bool {
        matches!(self, Self::Dirty)
    }

    /// Returns `true` when only retained 3D viewports need repainting.
    pub fn is_canvas3d_dirty(self) -> bool {
        matches!(self, Self::RepaintCanvas3D)
    }

    /// Returns `true` when either a full rebuild or a `Canvas3D`-only repaint is requested.
    pub fn needs_any_repaint(self) -> bool {
        !matches!(self, Self::Unchanged)
    }
}

/// Frame timing and metrics information passed to frame lifecycle callbacks.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct AppFrameInfo {
    pub frame_index: u64,
    pub viewport_width: f32,
    pub viewport_height: f32,
    pub dpr: f32,
    pub command_count: usize,
    pub dt: std::time::Duration,
}

/// Low-level lifecycle callbacks.
#[derive(Default)]
pub struct AppLifecycleHooks {
    pub on_start: Option<Box<dyn FnMut(&mut AppRuntime)>>,
    pub on_event: Option<Box<dyn FnMut(&PlatformEvent, &mut EventLoopControl, &mut AppRuntime)>>,
    pub on_frame: Option<Box<dyn FnMut(AppFrameInfo, &mut AppRuntime)>>,
    pub on_draw: Option<Box<dyn FnMut(&mut DisplayList)>>,
    pub on_exit: Option<Box<dyn FnMut(&mut AppRuntime)>>,
}

/// Low-level application orchestrator with fine-grained control over windowing, swapchain presentation,
/// lifecycle hooks, and manual frame pacing.
pub struct StrataApp {
    pub runtime: AppRuntime,
    pub window_config: WindowConfig,
    pub hooks: AppLifecycleHooks,
    pub compositor: SwapchainCompositor,
    pub presenter: SoftwareSurfacePresenter,
}

impl StrataApp {
    /// Creates a fluent low-level builder for configuring and launching a Strata app.
    pub fn builder() -> StrataAppBuilder {
        StrataAppBuilder::new()
    }

    /// Advances the runtime by a single frame and returns the generated display commands.
    pub fn step_frame(&mut self) -> &DisplayList {
        self.runtime.tick_frame();
        if let Some(ref mut on_draw) = self.hooks.on_draw {
            on_draw(&mut self.runtime.display_list);
        }
        &self.runtime.display_list
    }

    /// Dispatches a platform event into the runtime and lifecycle hooks.
    pub fn dispatch_event(&mut self, event: &PlatformEvent) -> bool {
        let mut control = EventLoopControl::Poll;
        if let Some(ref mut on_event) = self.hooks.on_event {
            on_event(event, &mut control, &mut self.runtime);
        }
        self.runtime.step_event(event)
    }

    /// Renders current frame to internal software surface buffer and returns immutable slice of BGRA pixels.
    pub fn render_to_buffer(&mut self) -> Result<&[u8], PresentError> {
        self.step_frame();
        self.compositor.render_and_present(
            &self.runtime.display_list,
            &mut self.presenter,
            true,
        )?;
        Ok(&self.presenter.backing_buffer)
    }

    /// Runs the application headlessly for a specified number of frames.
    pub fn run_headless(&mut self, frame_count: u64) -> Vec<AppFrameInfo> {
        if let Some(ref mut on_start) = self.hooks.on_start {
            on_start(&mut self.runtime);
        }
        let mut metrics = Vec::with_capacity(frame_count as usize);
        for _ in 0..frame_count {
            self.step_frame();
            let info = AppFrameInfo {
                frame_index: self.runtime.frame_count,
                viewport_width: self.runtime.viewport_width,
                viewport_height: self.runtime.viewport_height,
                dpr: self.runtime.dpr,
                command_count: self.runtime.display_list.commands.len(),
                dt: std::time::Duration::ZERO,
            };
            if let Some(ref mut on_frame) = self.hooks.on_frame {
                on_frame(info, &mut self.runtime);
            }
            metrics.push(info);
        }
        if let Some(ref mut on_exit) = self.hooks.on_exit {
            on_exit(&mut self.runtime);
        }
        metrics
    }

    /// Runs the platform window event loop with surface presentation.
    pub fn run_with_event_loop<E: EventLoop>(mut self, event_loop: &mut E) {
        println!(
            "[+] Launching Strata Native App: \"{}\"...",
            self.window_config.title
        );
        let mut window = LivePlatformWindow::new(self.window_config.clone());

        if let Some(ref mut on_start) = self.hooks.on_start {
            on_start(&mut self.runtime);
        }

        let _ = self
            .runtime
            .render_frame(&mut self.compositor, &mut self.presenter, true);

        let hooks = &mut self.hooks;
        let runtime = &mut self.runtime;
        let compositor = &mut self.compositor;
        let presenter = &mut self.presenter;

        event_loop.run(|event, control| {
            if let Some(ref mut on_event) = hooks.on_event {
                on_event(&event, control, runtime);
            }

            match event {
                PlatformEvent::WindowResized { width, height } => {
                    compositor.resize(width, height, runtime.dpr);
                    let _ = presenter.resize(width, height);
                }
                PlatformEvent::ScaleFactorChanged { scale_factor } => {
                    compositor.resize(
                        runtime.viewport_width as u32,
                        runtime.viewport_height as u32,
                        scale_factor,
                    );
                }
                PlatformEvent::WindowCloseRequested => {
                    *control = EventLoopControl::Exit;
                    return;
                }
                _ => {}
            }

            let needs_redraw = runtime.step_event(&event);

            if needs_redraw || window.is_redraw_requested() {
                if let Some(ref mut on_draw) = hooks.on_draw {
                    on_draw(&mut runtime.display_list);
                }
                let _ = runtime.render_frame(compositor, presenter, false);
                let _ = window.present_surface(
                    &presenter.backing_buffer,
                    presenter.width,
                    presenter.height,
                );
                if let Some(ref mut on_frame) = hooks.on_frame {
                    let info = AppFrameInfo {
                        frame_index: runtime.frame_count,
                        viewport_width: runtime.viewport_width,
                        viewport_height: runtime.viewport_height,
                        dpr: runtime.dpr,
                        command_count: runtime.display_list.commands.len(),
                        dt: std::time::Duration::ZERO,
                    };
                    on_frame(info, runtime);
                }
            }

            *control = EventLoopControl::Wait;
        });

        if let Some(ref mut on_exit) = self.hooks.on_exit {
            on_exit(&mut self.runtime);
        }
    }

    /// Runs the application using the native platform window (Wayland/X11 on Linux,
    /// Win32 on Windows, Cocoa on macOS), or headless fallback when running headless.
    pub fn run(mut self) {
        if std::env::var("STRATA_HEADLESS").is_ok() {
            let window = strata_platform::MockPlatformWindow::new(self.window_config.clone());
            let _ = crate::runtime::platforms::run_native_surface_window_loop(
                window,
                None::<fn() -> View>,
                self.runtime,
                self.compositor,
                self.presenter,
                |_, _| false,
                Some(&mut self.hooks),
            );
            return;
        }

        #[cfg(target_os = "linux")]
        {
            if std::env::var("WAYLAND_DISPLAY").is_ok() {
                if let Ok(window) = strata_platform::WaylandWindow::new(self.window_config.clone())
                {
                    let _ = crate::runtime::platforms::run_native_surface_window_loop(
                        window,
                        None::<fn() -> View>,
                        self.runtime,
                        self.compositor,
                        self.presenter,
                        |_, _| false,
                        Some(&mut self.hooks),
                    );
                    return;
                }
            }
            if std::env::var("DISPLAY").is_ok() {
                if let Ok(window) = strata_platform::X11Window::new(self.window_config.clone()) {
                    let _ = crate::runtime::platforms::run_native_surface_window_loop(
                        window,
                        None::<fn() -> View>,
                        self.runtime,
                        self.compositor,
                        self.presenter,
                        |_, _| false,
                        Some(&mut self.hooks),
                    );
                    return;
                }
            }
        }
        #[cfg(windows)]
        {
            if let Ok(window) = strata_platform::Win32Window::new(self.window_config.clone()) {
                let _ = crate::runtime::platforms::run_native_surface_window_loop(
                    window,
                    None::<fn() -> View>,
                    self.runtime,
                    self.compositor,
                    self.presenter,
                    |_, _| false,
                    Some(&mut self.hooks),
                );
                return;
            }
        }
        #[cfg(target_os = "macos")]
        {
            if let Ok(window) = strata_platform::MacOsWindow::new(self.window_config.clone()) {
                let _ = crate::runtime::platforms::run_native_surface_window_loop(
                    window,
                    None::<fn() -> View>,
                    self.runtime,
                    self.compositor,
                    self.presenter,
                    |_, _| false,
                    Some(&mut self.hooks),
                );
                return;
            }
        }
        let window = strata_platform::LivePlatformWindow::new(self.window_config.clone());
        let _ = crate::runtime::platforms::run_native_surface_window_loop(
            window,
            None::<fn() -> View>,
            self.runtime,
            self.compositor,
            self.presenter,
            |_, _| false,
            Some(&mut self.hooks),
        );
    }
}

/// Fluent builder for low-level application configuration and initialization.
pub struct StrataAppBuilder {
    window_config: WindowConfig,
    dpr: f32,
    hooks: AppLifecycleHooks,
}

impl Default for StrataAppBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl StrataAppBuilder {
    pub fn new() -> Self {
        Self {
            window_config: WindowConfig::default(),
            dpr: 1.0,
            hooks: AppLifecycleHooks::default(),
        }
    }

    pub fn with_window(mut self, config: WindowConfig) -> Self {
        self.window_config = config;
        self
    }

    pub fn with_dpr(mut self, dpr: f32) -> Self {
        self.dpr = dpr;
        self
    }

    /// Configures the pointer dwell delay before native hover tooltips (`title` / `alt`) appear.
    pub fn with_tooltip_delay(mut self, delay: std::time::Duration) -> Self {
        self.window_config.tooltip_delay = delay;
        self
    }

    /// Configures the pointer dwell delay in milliseconds before native hover tooltips appear.
    pub fn with_tooltip_delay_ms(mut self, delay_ms: u64) -> Self {
        self.window_config.tooltip_delay = std::time::Duration::from_millis(delay_ms);
        self
    }

    /// Configures visual styling and offset for native hover tooltips.
    pub fn with_tooltip_style(mut self, style: strata_platform::HoverTooltipStyle) -> Self {
        self.window_config.tooltip_style = style;
        self
    }

    pub fn on_start<F: FnMut(&mut AppRuntime) + 'static>(mut self, cb: F) -> Self {
        self.hooks.on_start = Some(Box::new(cb));
        self
    }

    pub fn on_event<F: FnMut(&PlatformEvent, &mut EventLoopControl, &mut AppRuntime) + 'static>(
        mut self,
        cb: F,
    ) -> Self {
        self.hooks.on_event = Some(Box::new(cb));
        self
    }

    pub fn on_frame<F: FnMut(AppFrameInfo, &mut AppRuntime) + 'static>(mut self, cb: F) -> Self {
        self.hooks.on_frame = Some(Box::new(cb));
        self
    }

    pub fn on_draw<F: FnMut(&mut DisplayList) + 'static>(mut self, cb: F) -> Self {
        self.hooks.on_draw = Some(Box::new(cb));
        self
    }

    pub fn on_exit<F: FnMut(&mut AppRuntime) + 'static>(mut self, cb: F) -> Self {
        self.hooks.on_exit = Some(Box::new(cb));
        self
    }

    pub fn build<F: FnOnce() -> View>(self, root: F) -> StrataApp {
        let width = self.window_config.width as f32;
        let height = self.window_config.height as f32;
        let mut runtime = AppRuntime::from_root(root, width, height, self.dpr);
        runtime.apply_window_config(&self.window_config);
        let presenter = SoftwareSurfacePresenter::new(
            self.window_config.width,
            self.window_config.height,
            SwapchainFormat::Bgra8Unorm,
        );
        let compositor = SwapchainCompositor::new(
            self.window_config.width,
            self.window_config.height,
            self.dpr,
        );

        StrataApp {
            runtime,
            window_config: self.window_config,
            hooks: self.hooks,
            compositor,
            presenter,
        }
    }
}