Skip to main content

kova_native/
application.rs

1//! Native application integration. No layout, rendering or event logic lives here.
2
3use kova_native_core::{Color, Duration, Instant, KovaError, KovaResult, Size};
4use kova_native_input::{KeyBinding, Keymap};
5use kova_native_platform::{
6    PlatformContext, PlatformEvent, PlatformHandler, PlatformWindow, PlatformWindowId,
7    WindowAttributes,
8};
9use kova_native_render::{GpuContext, Renderer, Scene, SceneStats, SurfaceOptions, WindowSurface};
10use kova_native_text::{TextStyle, TextSystem};
11use kova_native_widgets::{
12    DispatchContext, ElementTree, FrameContext, FrameStats, IntoElement, WindowCommand,
13};
14use std::cell::RefCell;
15use std::path::PathBuf;
16use std::rc::Rc;
17
18/// Native window and presentation settings, using the platform/renderer options.
19#[derive(Clone, Debug)]
20pub struct WindowOptions {
21    /// Native title, logical dimensions, minimum size and window attributes.
22    pub attributes: WindowAttributes,
23    /// Swapchain presentation settings, including vsync and frame latency.
24    pub surface: SurfaceOptions,
25    /// Color used to clear the window before drawing the scene.
26    pub background: Color,
27    /// Inherited text defaults for the root element tree.
28    pub text_style: TextStyle,
29    /// When true (the default) the root background, text color and text
30    /// size follow the current theme instead of `background`/`text_style`,
31    /// so theme switches restyle text that has no explicit color.
32    pub follow_theme: bool,
33}
34
35impl Default for WindowOptions {
36    fn default() -> Self {
37        let t = kova_native_widgets::theme();
38        Self {
39            attributes: WindowAttributes::default(),
40            surface: SurfaceOptions::default(),
41            background: t.background,
42            text_style: TextStyle {
43                size: t.font_size,
44                color: t.text,
45                ..Default::default()
46            },
47            follow_theme: true,
48        }
49    }
50}
51
52/// Measurements from frames actually presented to the native surface.
53#[derive(Clone, Copy, Debug, Default)]
54pub struct RunReport {
55    /// Frames successfully presented to the native swapchain.
56    pub presented_frames: u64,
57    /// Element-tree work performed for the last presented frame.
58    pub last_frame: FrameStats,
59    /// Primitive, culling and draw-call counts for the last presented scene.
60    pub last_scene: SceneStats,
61}
62
63/// Runs a retained UI in one native window. The event loop sleeps while idle;
64/// animations request redraws paced by the swapchain's presentation mode.
65#[derive(Default)]
66pub struct Application {
67    options: WindowOptions,
68    bindings: Vec<KeyBinding>,
69    on_file_drop: Option<Box<dyn FnMut(PathBuf)>>,
70    on_close_request: Option<Box<dyn FnMut() -> bool>>,
71    run_for: Option<Duration>,
72}
73
74impl Application {
75    /// Creates an application using the current theme and default window options.
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    /// Replaces the native window, presentation and root text settings.
81    pub fn window(mut self, options: WindowOptions) -> Self {
82        self.options = options;
83        self
84    }
85
86    /// Sets the native window's title.
87    pub fn title(mut self, title: impl Into<String>) -> Self {
88        self.options.attributes.title = title.into();
89        self
90    }
91
92    /// Initial inner size in logical pixels.
93    pub fn size(mut self, width: f32, height: f32) -> Self {
94        self.options.attributes.size = Size::new(width, height);
95        self
96    }
97
98    /// Appends shortcuts to the action keymap used by the focused element path.
99    ///
100    /// Register action handlers with [`kova_native_widgets::Interactive::on_action`].
101    pub fn key_bindings(mut self, bindings: impl IntoIterator<Item = KeyBinding>) -> Self {
102        self.bindings.extend(bindings);
103        self
104    }
105
106    /// Registers a callback for files dropped onto the application window.
107    ///
108    /// The operating system reports each dropped file separately, so the
109    /// callback runs once per file when multiple files are dropped together.
110    pub fn on_file_drop(mut self, callback: impl FnMut(PathBuf) + 'static) -> Self {
111        self.on_file_drop = Some(Box::new(callback));
112        self
113    }
114
115    /// Intercepts window close requests. Return `true` to close or `false` to
116    /// keep the window open. With no callback, close requests are accepted.
117    pub fn on_close_request(mut self, callback: impl FnMut() -> bool + 'static) -> Self {
118        self.on_close_request = Some(Box::new(callback));
119        self
120    }
121
122    /// Ends the event loop after a bounded duration, even when the UI is idle.
123    /// Useful for native startup smoke tests and automated example runs.
124    pub fn run_for(mut self, duration: Duration) -> Self {
125        self.run_for = Some(duration);
126        self
127    }
128
129    /// Mounts the root builder and runs until the window closes.
130    ///
131    /// Signals read directly by `build` rebuild its region. Read frequently
132    /// changing state in `text`/`bind` closures to update individual nodes.
133    /// State that must survive root rebuilds should be owned outside `build`.
134    ///
135    /// Call this on the main thread with an active native windowing session.
136    /// The returned [`RunReport`] describes frames actually presented. Platform,
137    /// GPU initialization and rendering failures are returned as [`KovaError`].
138    pub fn run<E: IntoElement>(
139        self,
140        mut build: impl FnMut() -> E + 'static,
141    ) -> KovaResult<RunReport> {
142        let _ = env_logger::Builder::from_env(
143            env_logger::Env::default().default_filter_or("kova_native=info"),
144        )
145        .try_init();
146        let shared = Rc::new(RefCell::new(Outcome::default()));
147        let mut keymap = Keymap::new();
148        keymap.extend(self.bindings);
149        let handler = Runner {
150            options: self.options,
151            build: Some(Box::new(move || build().into_any())),
152            state: None,
153            keymap,
154            on_file_drop: self.on_file_drop,
155            on_close_request: self.on_close_request,
156            run_for: self.run_for,
157            deadline: None,
158            shared: shared.clone(),
159        };
160        kova_native_platform::run(handler)?;
161        let mut outcome = shared.borrow_mut();
162        match outcome.error.take() {
163            Some(error) => Err(error),
164            None => Ok(outcome.report),
165        }
166    }
167}
168
169#[derive(Default)]
170struct Outcome {
171    report: RunReport,
172    error: Option<KovaError>,
173}
174
175struct NativeWindow {
176    window: PlatformWindow,
177    surface: WindowSurface,
178    gpu: GpuContext,
179    renderer: Renderer,
180    tree: ElementTree,
181    scene: Scene,
182    text: TextSystem,
183    clipboard: SystemClipboard,
184    occluded: bool,
185    animating: bool,
186    redraw_pending: bool,
187    retry_at: Option<Instant>,
188    shown: bool,
189    focused: bool,
190}
191
192struct SystemClipboard(kova_native_platform::Clipboard);
193
194impl kova_native_widgets::Clipboard for SystemClipboard {
195    fn read_text(&mut self) -> Option<String> {
196        self.0.read_text()
197    }
198    fn write_text(&mut self, text: &str) {
199        self.0.write_text(text);
200    }
201}
202
203struct Runner {
204    options: WindowOptions,
205    build: Option<Box<dyn FnMut() -> kova_native_widgets::AnyElement>>,
206    state: Option<NativeWindow>,
207    keymap: Keymap,
208    on_file_drop: Option<Box<dyn FnMut(PathBuf)>>,
209    on_close_request: Option<Box<dyn FnMut() -> bool>>,
210    run_for: Option<Duration>,
211    deadline: Option<Instant>,
212    shared: Rc<RefCell<Outcome>>,
213}
214
215impl Runner {
216    fn init_window(&mut self, cx: &mut PlatformContext) -> KovaResult<NativeWindow> {
217        log::debug!("kova-native: creating native window");
218        let window = cx.create_window(&self.options.attributes)?;
219        log::debug!("kova-native: creating GPU instance and surface");
220        let instance = GpuContext::create_instance();
221        let raw_surface = WindowSurface::create_surface(&instance, window.clone())?;
222        log::debug!("kova-native: requesting surface-compatible GPU");
223        let gpu = GpuContext::new(instance, Some(&raw_surface))?;
224        let (w, h) = window.physical_size();
225        let surface = WindowSurface::new(&gpu, raw_surface, w, h, self.options.surface)?;
226        let renderer = Renderer::new(&gpu);
227        log::debug!("kova-native: mounting element tree");
228        let build = self.build.take().expect("builder mounted once");
229        let mut tree = if self.options.follow_theme {
230            ElementTree::themed(build)
231        } else {
232            ElementTree::new(
233                build,
234                self.options.text_style.clone(),
235                self.options.background,
236            )
237        };
238        tree.set_viewport(window.logical_size(), window.scale_factor());
239        let waker = cx.waker();
240        tree.set_waker(move || waker.wake());
241        // Async tasks may be woken from worker threads.
242        let task_waker = cx.waker();
243        kova_native_core::task::set_wake_hook(move || task_waker.wake());
244        log::debug!("kova-native: native renderer ready");
245        Ok(NativeWindow {
246            window,
247            surface,
248            gpu,
249            renderer,
250            tree,
251            scene: Scene::new(),
252            text: TextSystem::new(),
253            clipboard: SystemClipboard(kova_native_platform::Clipboard::new()),
254            occluded: false,
255            animating: false,
256            redraw_pending: false,
257            retry_at: None,
258            shown: false,
259            focused: true,
260        })
261    }
262
263    fn draw(&mut self) {
264        let Some(state) = &mut self.state else { return };
265        state.redraw_pending = false;
266        let size = state.window.physical_size();
267        if state.occluded || size.0 == 0 || size.1 == 0 {
268            return;
269        }
270        if !state.shown {
271            log::debug!("kova-native: acquiring first surface frame");
272        }
273        // Acquire before consuming invalidation, so a missed surface frame
274        // cannot strand a dirty tree in an otherwise sleeping event loop.
275        let Some(frame) = state.surface.acquire(&state.gpu) else {
276            state.retry_at = Some(Instant::now() + Duration::from_millis(16));
277            return;
278        };
279        state.retry_at = None;
280        if !state.shown {
281            log::debug!("kova-native: building first scene");
282        }
283        let output = state.tree.frame(&mut FrameContext {
284            text: &mut state.text,
285            scene: &mut state.scene,
286            atlas: state.renderer.atlas(),
287            now: Instant::now(),
288        });
289        let view = frame.texture.create_view(&Default::default());
290        if !state.shown {
291            log::debug!("kova-native: submitting first scene");
292        }
293        state.renderer.render(
294            &state.gpu,
295            &state.scene,
296            &view,
297            state.surface.format(),
298            size,
299            if self.options.follow_theme {
300                kova_native_widgets::theme().background
301            } else {
302                self.options.background
303            },
304        );
305        state.window.pre_present_notify();
306        if !state.shown {
307            log::debug!("kova-native: presenting first scene");
308        }
309        state.gpu.queue.present(frame);
310        state.animating = output.animating;
311        state.window.set_cursor(output.cursor);
312        state
313            .window
314            .set_ime_allowed(state.focused && output.ime_area.is_some());
315        if let Some(area) = output.ime_area {
316            state.window.set_ime_cursor_area(area);
317        }
318        if !state.shown {
319            state.window.set_visible(true);
320            state.shown = true;
321        }
322        let mut shared = self.shared.borrow_mut();
323        shared.report.presented_frames += 1;
324        shared.report.last_frame = output.stats;
325        shared.report.last_scene = state.scene.stats();
326    }
327
328    fn apply_window_commands(&mut self, cx: &mut PlatformContext) {
329        let commands = self
330            .state
331            .as_mut()
332            .map(|s| s.tree.take_window_commands())
333            .unwrap_or_default();
334        for command in commands {
335            if matches!(command, WindowCommand::Close | WindowCommand::Quit) {
336                let accepted = self
337                    .on_close_request
338                    .as_mut()
339                    .is_none_or(|callback| callback());
340                if accepted {
341                    if let Some(state) = &self.state {
342                        let id = state.window.id();
343                        self.state = None;
344                        cx.destroy_window(id);
345                        cx.exit();
346                    }
347                }
348                continue;
349            }
350            let Some(state) = &self.state else { break };
351            match command {
352                WindowCommand::SetTitle(title) => state.window.set_title(&title),
353                WindowCommand::Minimize => state.window.minimize(),
354                WindowCommand::ToggleMaximize => {
355                    state.window.set_maximized(!state.window.is_maximized())
356                }
357                WindowCommand::Close | WindowCommand::Quit => unreachable!(),
358            }
359        }
360    }
361}
362
363impl PlatformHandler for Runner {
364    fn init(&mut self, cx: &mut PlatformContext) {
365        match self.init_window(cx) {
366            Ok(state) => {
367                self.state = Some(state);
368                self.deadline = self.run_for.map(|d| Instant::now() + d);
369                // Hidden Win32 windows do not receive WM_PAINT redraw requests.
370                // Present the initial frame directly before revealing the window.
371                self.draw();
372                log::debug!("kova-native: event loop initialized");
373            }
374            Err(error) => {
375                self.shared.borrow_mut().error = Some(error);
376                cx.exit();
377            }
378        }
379    }
380
381    fn window_event(
382        &mut self,
383        cx: &mut PlatformContext,
384        id: PlatformWindowId,
385        event: PlatformEvent,
386    ) {
387        if let PlatformEvent::CloseRequested = &event
388            && !self
389                .on_close_request
390                .as_mut()
391                .is_none_or(|callback| callback())
392        {
393            return;
394        }
395        let Some(state) = &mut self.state else { return };
396        if state.window.id() != id {
397            return;
398        }
399        match event {
400            PlatformEvent::RedrawRequested => self.draw(),
401            PlatformEvent::CloseRequested => {
402                self.state = None;
403                cx.destroy_window(id);
404                cx.exit();
405            }
406            PlatformEvent::Resized { width, height } => {
407                state.surface.resize(&state.gpu, width, height);
408                state
409                    .tree
410                    .set_viewport(state.window.logical_size(), state.window.scale_factor());
411                state.redraw_pending = false;
412            }
413            PlatformEvent::ScaleFactorChanged(scale) => {
414                let (w, h) = state.window.physical_size();
415                state.surface.resize(&state.gpu, w, h);
416                state.tree.set_viewport(state.window.logical_size(), scale);
417                state.redraw_pending = false;
418            }
419            PlatformEvent::Occluded(value) => {
420                state.occluded = value;
421                state.redraw_pending = false;
422                if !value {
423                    state.window.request_redraw();
424                }
425            }
426            PlatformEvent::Focused(false) => {
427                state.focused = false;
428                self.keymap.clear_pending();
429                state.tree.cancel_pointer_input(&mut state.text);
430                state.window.set_ime_allowed(false);
431            }
432            PlatformEvent::Focused(true) => {
433                state.focused = true;
434                state.window.request_redraw();
435            }
436            PlatformEvent::Input(event) => {
437                let result = state.tree.dispatch(
438                    &event,
439                    &mut DispatchContext {
440                        text: &mut state.text,
441                        clipboard: &mut state.clipboard,
442                        keymap: &mut self.keymap,
443                        now: Instant::now(),
444                    },
445                );
446                for action in result.unhandled_actions {
447                    log::debug!("kova-native: unhandled action {}", action.name());
448                }
449            }
450            PlatformEvent::FileDropped(path) => {
451                if let Some(callback) = &mut self.on_file_drop {
452                    callback(path);
453                }
454            }
455        }
456        self.apply_window_commands(cx);
457    }
458
459    fn about_to_wait(&mut self, cx: &mut PlatformContext) {
460        let now = Instant::now();
461        if let Some(deadline) = self.deadline {
462            if now >= deadline {
463                log::debug!("kova-native: bounded native run completed");
464                cx.exit();
465                return;
466            }
467            cx.wake_at(deadline);
468        }
469        self.apply_window_commands(cx);
470        let Some(state) = &mut self.state else { return };
471        let (w, h) = state.window.physical_size();
472        if state.occluded || w == 0 || h == 0 || state.redraw_pending {
473            return;
474        }
475        if let Some(retry) = state.retry_at
476            && retry > now
477        {
478            cx.wake_at(retry);
479            return;
480        }
481        // Timers registered by handlers since the last frame count too.
482        let timed = match state.tree.next_deadline() {
483            Some(at) if at > now => {
484                cx.wake_at(at);
485                false
486            }
487            Some(_) => true,
488            None => false,
489        };
490        if state.tree.needs_frame() || state.animating || timed || state.retry_at.is_some() {
491            if !state.shown {
492                // Retry initial acquisition without relying on hidden-window
493                // redraw events (the retry deadline above prevents spinning).
494                self.draw();
495                return;
496            }
497            state.window.request_redraw();
498            state.redraw_pending = true;
499        }
500    }
501}