Skip to main content

strata/runtime/
platforms.rs

1//! Native windowing backends for X11, Wayland, Win32, and macOS Cocoa.
2
3use super::*;
4
5pub(crate) fn resolved_cursor_at(
6    runtime: &AppRuntime,
7    x: f32,
8    y: f32,
9) -> strata_platform::window::CursorIcon {
10    let mut cached_hit: Option<Option<Vec<usize>>> = None;
11    let is_over_scrollbar = runtime.active_scrollbars.iter().rev().any(|bar| {
12        bar.max_scroll_y > 1.0
13            && bar.clip_bounds.contains_point(x, y)
14            && (x >= bar.track_bounds.x
15                && x <= bar.bounds.x + bar.bounds.width + 1.0
16                && y >= bar.track_bounds.y
17                && y <= bar.track_bounds.y + bar.track_bounds.height)
18            && runtime.scrollbar_owns_point(bar, x, y, &mut cached_hit)
19    });
20    if is_over_scrollbar {
21        strata_platform::window::CursorIcon::Default
22    } else {
23        AppRuntime::hit_test_cursor(&runtime.root_blueprint, &runtime.layout_root, x, y)
24    }
25}
26
27#[inline]
28fn try_retained_canvas3d_redraw_only(
29    runtime: &mut AppRuntime,
30    x: f32,
31    y: f32,
32    needs_rebuild: &mut bool,
33    needs_redraw: &mut bool,
34) {
35    if runtime.target_is_retained_canvas3d(x, y) && !strata_dom::reactive::has_dirty_signals() {
36        runtime.mark_viewport_3d_dirty();
37        *needs_redraw = true;
38    } else {
39        *needs_rebuild = true;
40    }
41}
42
43/// Dispatches a native platform event into the AppRuntime, updating geometry, focus, input, and styling.
44/// Returns `(needs_rebuild, needs_redraw, should_exit)`.
45pub fn dispatch_native_platform_event<E>(
46    event: &strata_platform::PlatformEvent,
47    runtime: &mut AppRuntime,
48    compositor: &mut SwapchainCompositor,
49    presenter: &mut SoftwareSurfacePresenter,
50    event_handler: &mut E,
51) -> (bool, bool, bool)
52where
53    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool,
54{
55    let mut needs_rebuild = false;
56    let mut needs_redraw = false;
57    let mut should_exit = false;
58
59    if event_handler(event, runtime) {
60        needs_rebuild = true;
61    }
62
63    match event {
64        strata_platform::PlatformEvent::WindowCloseRequested => {
65            should_exit = true;
66        }
67        strata_platform::PlatformEvent::WindowResized {
68            width: w,
69            height: h,
70        } => {
71            let wf = (*w).max(1) as f32;
72            let hf = (*h).max(1) as f32;
73            compositor.resize(*w, *h, runtime.dpr);
74            let _ = presenter.resize(*w, *h);
75            let size_changed = (runtime.viewport_width - wf).abs() > 0.01
76                || (runtime.viewport_height - hf).abs() > 0.01;
77            runtime.viewport_width = wf;
78            runtime.viewport_height = hf;
79            if size_changed {
80                let signals_before = strata_dom::reactive::has_dirty_signals();
81                runtime.unapply_scroll_offsets();
82                runtime.layout_root.compute_layout(wf, hf);
83                AppRuntime::sync_layout_to_ir(&runtime.layout_root, &mut runtime.ir_graph);
84                runtime.apply_viewport_clamps();
85                runtime.apply_scroll_offsets();
86                runtime
87                    .spatial_index
88                    .rebuild(&runtime.root_blueprint, &runtime.layout_root);
89                let resize_fired = runtime.dispatch_resize_observers();
90                if resize_fired
91                    || (!signals_before && strata_dom::reactive::has_dirty_signals())
92                {
93                    needs_rebuild = true;
94                }
95                runtime.mark_paint_dirty();
96            }
97            needs_redraw = true;
98        }
99        strata_platform::PlatformEvent::ScaleFactorChanged { scale_factor } => {
100            compositor.resize(
101                runtime.viewport_width as u32,
102                runtime.viewport_height as u32,
103                *scale_factor,
104            );
105            runtime.dpr = *scale_factor;
106            needs_redraw = true;
107        }
108        strata_platform::PlatformEvent::Scroll {
109            delta_x, delta_y, ..
110        } => {
111            let (px, py) = runtime.last_mouse_pos;
112            let (wheel_handled, scroll_changed) =
113                runtime.dispatch_smooth_scroll_action(px, py, *delta_x, *delta_y);
114            if wheel_handled {
115                try_retained_canvas3d_redraw_only(
116                    runtime,
117                    px,
118                    py,
119                    &mut needs_rebuild,
120                    &mut needs_redraw,
121                );
122            }
123            if runtime.dismiss_hover_tooltip_and_repaint() {
124                needs_redraw = true;
125            }
126            if scroll_changed {
127                needs_redraw = true;
128            }
129        }
130        strata_platform::PlatformEvent::AnimationTick => {
131            let scroll_changed = runtime.poll_smooth_scroll();
132            let anim_changed = runtime.poll_animations();
133            let caret_changed = runtime.poll_caret_blink();
134            let tooltip_changed = runtime.poll_hover_tooltip();
135            let mcp_changed = if let Some(ref mut c) = runtime.mcp_cursor {
136                c.poll_tick()
137            } else {
138                false
139            };
140            if scroll_changed || anim_changed || caret_changed || tooltip_changed || mcp_changed {
141                needs_redraw = true;
142            }
143            if strata_dom::reactive::has_dirty_signals() {
144                needs_rebuild = true;
145                needs_redraw = true;
146            }
147        }
148        strata_platform::PlatformEvent::DoubleClick { button, x, y } => {
149            let _btn_idx = button.to_button_index();
150            if *button == strata_platform::MouseButton::Left {
151                let region = AppRuntime::hit_test_property(
152                    &runtime.root_blueprint,
153                    &runtime.layout_root,
154                    *x,
155                    *y,
156                    "data-app-region",
157                );
158                if region.as_deref() == Some("drag") {
159                    needs_rebuild = true;
160                }
161            }
162            if runtime.dispatch_dblclick(*x, *y) {
163                needs_rebuild = true;
164            }
165        }
166        strata_platform::PlatformEvent::MouseDown { button, x, y } => {
167            runtime.last_mouse_pos = (*x, *y);
168            if runtime.dismiss_hover_tooltip_and_repaint() {
169                needs_redraw = true;
170            }
171            let btn_idx = button.to_button_index();
172            if *button == strata_platform::MouseButton::Left {
173                runtime.is_mouse_down = true;
174                if runtime.check_scrollbar_thumb_press(*x, *y) {
175                    needs_redraw = true;
176                } else {
177                    runtime.begin_window_drag_candidate(*x, *y);
178                    let action = runtime.dispatch_pointer_down_action_with_button_and_modifiers(
179                        *x,
180                        *y,
181                        btn_idx,
182                        Default::default(),
183                    );
184                    if action.needs_rebuild() {
185                        needs_rebuild = true;
186                    } else if action.needs_redraw() {
187                        needs_redraw = true;
188                    }
189                    if runtime.dispatch_mouse_click(*x, *y, btn_idx, 1) {
190                        needs_rebuild = true;
191                    }
192                    if runtime.drain_edit_commands() {
193                        needs_rebuild = true;
194                    }
195                    if !needs_rebuild && runtime.restyle_for_active_change() {
196                        needs_redraw = true;
197                    }
198                }
199            } else if *button == strata_platform::MouseButton::Middle {
200                let action = runtime.dispatch_pointer_down_action_with_button_and_modifiers(
201                    *x,
202                    *y,
203                    btn_idx,
204                    Default::default(),
205                );
206                if action.needs_rebuild() {
207                    needs_rebuild = true;
208                } else if action.needs_redraw() {
209                    needs_redraw = true;
210                }
211                if runtime.dispatch_mouse_click(*x, *y, btn_idx, 1) {
212                    needs_rebuild = true;
213                }
214            } else if *button == strata_platform::MouseButton::Right {
215                let action = runtime.dispatch_pointer_down_action_with_button_and_modifiers(
216                    *x,
217                    *y,
218                    btn_idx,
219                    Default::default(),
220                );
221                if action.needs_rebuild() {
222                    needs_rebuild = true;
223                } else if action.needs_redraw() {
224                    needs_redraw = true;
225                }
226                if runtime.dispatch_context_menu(*x, *y) {
227                    needs_rebuild = true;
228                }
229                if runtime.drain_edit_commands() {
230                    needs_rebuild = true;
231                }
232            }
233            runtime.current_cursor = resolved_cursor_at(runtime, *x, *y);
234        }
235        strata_platform::PlatformEvent::MouseUp { button, x, y } => {
236            runtime.last_mouse_pos = (*x, *y);
237            let btn_idx = button.to_button_index();
238            let was_mouse_down = runtime.is_mouse_down;
239            if *button == strata_platform::MouseButton::Left {
240                runtime.is_mouse_down = false;
241            }
242            if runtime.scrollbar_drag.is_some() {
243                runtime.scrollbar_drag = None;
244                needs_redraw = true;
245            }
246            runtime.pending_window_drag = None;
247            let action = runtime.dispatch_pointer_up_action_with_button(*x, *y, btn_idx);
248            if action.needs_rebuild() {
249                needs_rebuild = true;
250            } else if action.needs_redraw() {
251                needs_redraw = true;
252            }
253            if was_mouse_down && !needs_rebuild && runtime.restyle_for_active_change() {
254                needs_redraw = true;
255            }
256            runtime.current_cursor = resolved_cursor_at(runtime, *x, *y);
257        }
258        strata_platform::PlatformEvent::MouseMove { x, y } => {
259            runtime.last_mouse_pos = (*x, *y);
260            if runtime.scrollbar_drag.is_some() {
261                if runtime.poll_scrollbar_drag(*x, *y) {
262                    needs_redraw = true;
263                }
264            } else {
265                if runtime.poll_window_drag(*x, *y) {
266                    needs_rebuild = true;
267                }
268                let action = runtime.dispatch_pointer_move_action(*x, *y);
269                if action.needs_rebuild() {
270                    try_retained_canvas3d_redraw_only(
271                        runtime,
272                        *x,
273                        *y,
274                        &mut needs_rebuild,
275                        &mut needs_redraw,
276                    );
277                } else if action.needs_redraw() {
278                    needs_redraw = true;
279                }
280                if runtime.update_hover(*x, *y) {
281                    if runtime.hover_is_paint_only() {
282                        needs_redraw = true;
283                    } else {
284                        needs_rebuild = true;
285                    }
286                }
287                runtime.current_cursor = resolved_cursor_at(runtime, *x, *y);
288            }
289        }
290        strata_platform::PlatformEvent::CursorLeft => {
291            runtime.is_mouse_down = false;
292            runtime.current_cursor = strata_platform::window::CursorIcon::Default;
293            if runtime.clear_hover() {
294                if runtime.hover_is_paint_only() {
295                    needs_redraw = true;
296                } else {
297                    needs_rebuild = true;
298                }
299            }
300        }
301        strata_platform::PlatformEvent::KeyDown { .. }
302        | strata_platform::PlatformEvent::KeyUp { .. }
303        | strata_platform::PlatformEvent::ReceivedCharacter(_)
304        | strata_platform::PlatformEvent::ImePreedit { .. }
305        | strata_platform::PlatformEvent::ImeCommit(_) => {
306            if matches!(event, strata_platform::PlatformEvent::KeyDown { .. })
307                && runtime.dismiss_hover_tooltip_and_repaint()
308            {
309                needs_redraw = true;
310            }
311            let res = runtime.dispatch_key_event(event);
312            if res.needs_rebuild() {
313                needs_rebuild = true;
314            } else if res.needs_redraw() {
315                needs_redraw = true;
316            }
317        }
318        strata_platform::PlatformEvent::WindowMaximized(_) => {
319            needs_rebuild = true;
320            needs_redraw = true;
321        }
322        strata_platform::PlatformEvent::FileDrop(paths) => {
323            if runtime.dismiss_hover_tooltip_and_repaint() {
324                needs_redraw = true;
325            }
326            if runtime.dispatch_file_drop(paths.clone()) {
327                needs_rebuild = true;
328                needs_redraw = true;
329            }
330        }
331        _ => {}
332    }
333
334    (needs_rebuild, needs_redraw, should_exit)
335}
336
337impl AppRuntime {
338    /// Dynamically computes the appropriate thread sleep duration based on runtime activity state.
339    /// Returns:
340    /// - 16ms if animations, smooth scrolling, scrollbar dragging, window dragging, active interactions, or dirty signals are active.
341    /// - 50ms if a text input currently has active focus (to service responsive caret blinking).
342    /// - 200ms if the runtime is completely idle (dropping CPU consumption to ~0%).
343    pub fn compute_idle_sleep(&self, was_active: bool) -> std::time::Duration {
344        let mut base = if was_active
345            || self.has_active_animations()
346            || self.active_smooth_scroll.is_some()
347            || self.scrollbar_drag.is_some()
348            || self.pending_window_drag.is_some()
349            || self.drag_selection_active
350            || strata_dom::reactive::has_dirty_signals()
351        {
352            std::time::Duration::from_millis(16)
353        } else if self.active_focus.is_some() {
354            std::time::Duration::from_millis(50)
355        } else {
356            std::time::Duration::from_millis(200)
357        };
358        if let Some(due) = self.next_hover_tooltip_due_in() {
359            base = base.min(due.max(std::time::Duration::from_millis(1)));
360        }
361        if let Some(next_timer) = strata_js::web::time_until_next_timer() {
362            base.min(next_timer.max(std::time::Duration::from_millis(1)))
363        } else {
364            base
365        }
366    }
367}
368
369/// Runs an interactive native window event loop against any NativeSurfaceWindow implementation,
370/// pacing frames, evaluating reactive updates, and blitting pixel buffers.
371pub fn run_native_surface_window_loop<W, F, E>(
372    mut window: W,
373    mut root_fn: Option<F>,
374    mut runtime: AppRuntime,
375    mut compositor: SwapchainCompositor,
376    mut presenter: SoftwareSurfacePresenter,
377    mut event_handler: E,
378    mut hooks: Option<&mut AppLifecycleHooks>,
379) -> Result<(), String>
380where
381    W: strata_platform::NativeSurfaceWindow,
382    F: FnMut() -> View + 'static,
383    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool,
384{
385    // Initial frame presentation
386    let _ = runtime.render_frame(&mut compositor, &mut presenter, true);
387    let _ = window.present_surface(&presenter.backing_buffer, presenter.width, presenter.height);
388
389    if let Some(ref mut h) = hooks {
390        if let Some(ref mut on_start) = h.on_start {
391            on_start(&mut runtime);
392        }
393        if let Some(ref mut on_frame) = h.on_frame {
394            let info = AppFrameInfo {
395                frame_index: runtime.frame_count,
396                viewport_width: runtime.viewport_width,
397                viewport_height: runtime.viewport_height,
398                dpr: runtime.dpr,
399                command_count: runtime.display_list.commands.len(),
400                dt: std::time::Duration::ZERO,
401            };
402            on_frame(info, &mut runtime);
403        }
404    }
405
406    println!(
407        "[OK] Strata Native Window active: {}x{} physical pixels, {} commands presented.",
408        presenter.width,
409        presenter.height,
410        runtime.display_list.commands.len()
411    );
412
413    let max_headless_frames = if std::env::var("STRATA_HEADLESS").is_ok() {
414        Some(
415            std::env::var("STRATA_HEADLESS_EXIT_AFTER_FRAMES")
416                .ok()
417                .and_then(|s| s.parse::<u64>().ok())
418                .unwrap_or(1),
419        )
420    } else {
421        None
422    };
423    let mut frames_presented: u64 = 1;
424
425    #[cfg(feature = "hot-reload")]
426    let mut hmr_ctrl = HmrRuntimeController::from_env(|| {});
427
428    let mut running = true;
429    while running {
430        if let Some(max_f) = max_headless_frames {
431            if frames_presented >= max_f {
432                break;
433            }
434        }
435        let events = window.poll_events();
436        let mut needs_rebuild = false;
437        let mut needs_redraw = false;
438
439        #[cfg(feature = "hot-reload")]
440        if let Some(ref mut hmr) = hmr_ctrl {
441            if let Some(outcome) = hmr.poll_and_apply(&mut runtime) {
442                if outcome.ok {
443                    needs_redraw = true;
444                }
445            }
446            if hmr.shutdown_requested() {
447                break;
448            }
449            if hmr.take_dirty_signals() {
450                needs_rebuild = true;
451                needs_redraw = true;
452            }
453        }
454
455        for event in events {
456            if let Some(ref mut h) = hooks {
457                if let Some(ref mut on_ev) = h.on_event {
458                    let mut control = strata_platform::EventLoopControl::Poll;
459                    on_ev(&event, &mut control, &mut runtime);
460                    if control == strata_platform::EventLoopControl::Exit {
461                        running = false;
462                        break;
463                    }
464                }
465            }
466
467            if let strata_platform::PlatformEvent::DoubleClick { button, x, y } = event {
468                if button == strata_platform::MouseButton::Left {
469                    let region = AppRuntime::hit_test_property(
470                        &runtime.root_blueprint,
471                        &runtime.layout_root,
472                        x,
473                        y,
474                        "data-app-region",
475                    );
476                    let is_drag = region.as_deref() == Some("drag")
477                        || runtime.csd_controller.hit_test(
478                            runtime.viewport_width,
479                            runtime.viewport_height,
480                            x,
481                            y,
482                        ) == strata_platform::CsdHitZone::Titlebar;
483                    if is_drag {
484                        let is_max = window.toggle_maximize();
485                        window.push_event(strata_platform::PlatformEvent::WindowMaximized(is_max));
486                        needs_rebuild = true;
487                    }
488                }
489            }
490
491            if let strata_platform::PlatformEvent::MouseMove { x, y } = event {
492                if runtime.poll_window_drag(x, y) {
493                    window.begin_window_drag(x, y);
494                }
495            }
496
497            let (reb, red, exit) = dispatch_native_platform_event(
498                &event,
499                &mut runtime,
500                &mut compositor,
501                &mut presenter,
502                &mut event_handler,
503            );
504            if reb {
505                needs_rebuild = true;
506            }
507            if red {
508                needs_redraw = true;
509            }
510            if exit {
511                running = false;
512                break;
513            }
514        }
515
516        if !running {
517            break;
518        }
519
520        let anim_changed = runtime.poll_animations();
521        let scroll_changed = runtime.poll_smooth_scroll();
522        let caret_changed = runtime.poll_caret_blink();
523        let timers_fired = strata_js::web::tick_timers() > 0;
524        if timers_fired || strata_dom::reactive::has_dirty_signals() {
525            needs_rebuild = true;
526            needs_redraw = true;
527        }
528        if anim_changed || scroll_changed || caret_changed {
529            needs_redraw = true;
530        }
531
532        if needs_rebuild {
533            if runtime.sync_dynamic_text() {
534                let _ = strata_dom::reactive::take_dirty_signals();
535                runtime.mark_paint_dirty();
536                let _ = runtime.render_frame(&mut compositor, &mut presenter, false);
537                let _ = window.present_surface(
538                    &presenter.backing_buffer,
539                    presenter.width,
540                    presenter.height,
541                );
542            } else {
543                #[cfg(feature = "hot-reload")]
544                let hot_view = hmr_ctrl.as_ref().and_then(|h| h.render_active_view());
545                #[cfg(not(feature = "hot-reload"))]
546                let hot_view: Option<View> = None;
547
548                if let Some(view) = hot_view {
549                    let _ = strata_dom::reactive::take_dirty_signals();
550                    runtime.update_view(view);
551                    let _ = runtime.render_frame(&mut compositor, &mut presenter, true);
552                    let _ = window.present_surface(
553                        &presenter.backing_buffer,
554                        presenter.width,
555                        presenter.height,
556                    );
557                } else if let Some(ref mut f) = root_fn {
558                    let _ = strata_dom::reactive::take_dirty_signals();
559                    runtime.update_root(f);
560                    let _ = runtime.render_frame(&mut compositor, &mut presenter, true);
561                    let _ = window.present_surface(
562                        &presenter.backing_buffer,
563                        presenter.width,
564                        presenter.height,
565                    );
566                } else {
567                    runtime.mark_paint_dirty();
568                    let _ = runtime.render_frame(&mut compositor, &mut presenter, true);
569                    let _ = window.present_surface(
570                        &presenter.backing_buffer,
571                        presenter.width,
572                        presenter.height,
573                    );
574                }
575            }
576        } else if needs_redraw || window.is_redraw_requested() {
577            // A per-frame draw hook edits the display list, so it forces a fresh compile.
578            let has_draw_hook = hooks.as_ref().is_some_and(|h| h.on_draw.is_some());
579            if needs_redraw || has_draw_hook {
580                runtime.mark_paint_dirty();
581            }
582            if let Some(ref mut h) = hooks {
583                if let Some(ref mut on_draw) = h.on_draw {
584                    on_draw(&mut runtime.display_list);
585                }
586            }
587            let _ = runtime.render_frame(&mut compositor, &mut presenter, false);
588            let _ = window.present_surface(
589                &presenter.backing_buffer,
590                presenter.width,
591                presenter.height,
592            );
593            if let Some(ref mut h) = hooks {
594                if let Some(ref mut on_frame) = h.on_frame {
595                    let info = AppFrameInfo {
596                        frame_index: runtime.frame_count,
597                        viewport_width: runtime.viewport_width,
598                        viewport_height: runtime.viewport_height,
599                        dpr: runtime.dpr,
600                        command_count: runtime.display_list.commands.len(),
601                        dt: std::time::Duration::ZERO,
602                    };
603                    on_frame(info, &mut runtime);
604                }
605            }
606        }
607
608        frames_presented += 1;
609        if max_headless_frames.is_none() {
610            let is_active = anim_changed
611                || scroll_changed
612                || caret_changed
613                || timers_fired
614                || needs_rebuild
615                || needs_redraw;
616            std::thread::sleep(runtime.compute_idle_sleep(is_active));
617        }
618    }
619
620    if let Some(ref mut h) = hooks {
621        if let Some(ref mut on_exit) = h.on_exit {
622            on_exit(&mut runtime);
623        }
624    }
625
626    Ok(())
627}
628
629#[cfg(target_os = "linux")]
630pub fn launch_x11<F>(root_fn: F, config: WindowConfig) -> Result<(), String>
631where
632    F: FnMut() -> View + 'static,
633{
634    launch_x11_with_events(root_fn, config, |_, _| false)
635}
636
637#[cfg(target_os = "linux")]
638/// Launches an interactive native X11 desktop window on Linux with a custom event hook.
639pub fn launch_x11_with_events<F, E>(
640    mut root_fn: F,
641    config: WindowConfig,
642    event_handler: E,
643) -> Result<(), String>
644where
645    F: FnMut() -> View + 'static,
646    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool + 'static,
647{
648    println!(
649        "[+] Launching Strata Native Desktop Window on X11: \"{}\"...",
650        config.title
651    );
652    let x11_window = strata_platform::x11_window::X11Window::new(config.clone())?;
653    let view = strata_dom::with_root_component_scope(&mut root_fn);
654    let width = config.width as f32;
655    let height = config.height as f32;
656    let mut runtime = AppRuntime::new(view, width, height, 1.0);
657    runtime.apply_window_config(&config);
658    let presenter =
659        SoftwareSurfacePresenter::new(config.width, config.height, SwapchainFormat::Bgra8Unorm);
660    let compositor = SwapchainCompositor::new(config.width, config.height, 1.0);
661
662    run_native_surface_window_loop(
663        x11_window,
664        Some(root_fn),
665        runtime,
666        compositor,
667        presenter,
668        event_handler,
669        None,
670    )
671}
672
673#[cfg(target_os = "linux")]
674/// Launches an interactive native Wayland desktop window on Linux displaying the Strata application.
675pub fn launch_wayland<F>(root_fn: F, config: WindowConfig) -> Result<(), String>
676where
677    F: FnMut() -> View + 'static,
678{
679    launch_wayland_with_events(root_fn, config, |_, _| false)
680}
681
682#[cfg(target_os = "linux")]
683/// Launches an interactive native Wayland desktop window on Linux with a custom event hook.
684pub fn launch_wayland_with_events<F, E>(
685    mut root_fn: F,
686    config: WindowConfig,
687    event_handler: E,
688) -> Result<(), String>
689where
690    F: FnMut() -> View + 'static,
691    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool + 'static,
692{
693    println!(
694        "[+] Launching Strata Native Desktop Window on Wayland: \"{}\"...",
695        config.title
696    );
697    let wayland_window = strata_platform::WaylandWindow::new(config.clone())?;
698    let view = strata_dom::with_root_component_scope(&mut root_fn);
699    let width = config.width as f32;
700    let height = config.height as f32;
701    let dpr = wayland_window.scale_factor();
702    let mut runtime = AppRuntime::new(view, width, height, dpr);
703    runtime.apply_window_config(&config);
704    let presenter =
705        SoftwareSurfacePresenter::new(config.width, config.height, SwapchainFormat::Bgra8Unorm);
706    let compositor = SwapchainCompositor::new(config.width, config.height, dpr);
707
708    run_native_surface_window_loop(
709        wayland_window,
710        Some(root_fn),
711        runtime,
712        compositor,
713        presenter,
714        event_handler,
715        None,
716    )
717}
718
719#[cfg(windows)]
720/// Launches an interactive native Win32 desktop window on Windows displaying the Strata application.
721pub fn launch_win32<F>(root_fn: F, config: WindowConfig) -> Result<(), String>
722where
723    F: FnMut() -> View + 'static,
724{
725    launch_win32_with_events(root_fn, config, |_, _| false)
726}
727
728#[cfg(windows)]
729/// Launches an interactive native Win32 desktop window on Windows with a custom event hook.
730pub fn launch_win32_with_events<F, E>(
731    mut root_fn: F,
732    config: WindowConfig,
733    event_handler: E,
734) -> Result<(), String>
735where
736    F: FnMut() -> View + 'static,
737    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool + 'static,
738{
739    println!(
740        "[+] Launching Strata Native Desktop Window on Windows (Win32): \"{}\"...",
741        config.title
742    );
743    let win32_window = strata_platform::Win32Window::new(config.clone())?;
744    let view = strata_dom::with_root_component_scope(|| root_fn());
745    let width = config.width as f32;
746    let height = config.height as f32;
747    let dpr = win32_window.scale_factor();
748    let mut runtime = AppRuntime::new(view, width, height, dpr);
749    runtime.apply_window_config(&config);
750    let presenter =
751        SoftwareSurfacePresenter::new(config.width, config.height, SwapchainFormat::Bgra8Unorm);
752    let compositor = SwapchainCompositor::new(config.width, config.height, dpr);
753
754    run_native_surface_window_loop(
755        win32_window,
756        Some(root_fn),
757        runtime,
758        compositor,
759        presenter,
760        event_handler,
761        None,
762    )
763}
764
765#[cfg(target_os = "macos")]
766/// Launches an interactive native macOS Cocoa desktop window displaying the Strata application.
767pub fn launch_macos<F>(root_fn: F, config: WindowConfig) -> Result<(), String>
768where
769    F: FnMut() -> View + 'static,
770{
771    launch_macos_with_events(root_fn, config, |_, _| false)
772}
773
774#[cfg(target_os = "macos")]
775/// Launches an interactive native macOS Cocoa desktop window with a custom event hook.
776pub fn launch_macos_with_events<F, E>(
777    mut root_fn: F,
778    config: WindowConfig,
779    event_handler: E,
780) -> Result<(), String>
781where
782    F: FnMut() -> View + 'static,
783    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool + 'static,
784{
785    println!(
786        "[+] Launching Strata Native Desktop Window on macOS (Cocoa): \"{}\"...",
787        config.title
788    );
789    let macos_window = strata_platform::MacOsWindow::new(config.clone())?;
790    let view = strata_dom::with_root_component_scope(|| root_fn());
791    let width = config.width as f32;
792    let height = config.height as f32;
793    let dpr = macos_window.scale_factor();
794    let mut runtime = AppRuntime::new(view, width, height, dpr);
795    runtime.apply_window_config(&config);
796    let presenter =
797        SoftwareSurfacePresenter::new(config.width, config.height, SwapchainFormat::Bgra8Unorm);
798    let compositor = SwapchainCompositor::new(config.width, config.height, dpr);
799
800    run_native_surface_window_loop(
801        macos_window,
802        Some(root_fn),
803        runtime,
804        compositor,
805        presenter,
806        event_handler,
807        None,
808    )
809}
810
811#[cfg(target_os = "android")]
812/// Launches an interactive native Android application window via Android NDK NativeActivity.
813pub fn launch_android<F>(
814    native_window: *mut std::ffi::c_void,
815    root_fn: F,
816    config: WindowConfig,
817) -> Result<(), String>
818where
819    F: FnMut() -> View + 'static,
820{
821    launch_android_with_events(native_window, root_fn, config, |_, _| false)
822}
823
824#[cfg(target_os = "android")]
825/// Launches an interactive native Android application window with a custom event hook.
826pub fn launch_android_with_events<F, E>(
827    native_window: *mut std::ffi::c_void,
828    mut root_fn: F,
829    config: WindowConfig,
830    event_handler: E,
831) -> Result<(), String>
832where
833    F: FnMut() -> View + 'static,
834    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool + 'static,
835{
836    let android_window = strata_platform::AndroidWindow::new(native_window, config.clone())?;
837    let view = strata_dom::with_root_component_scope(|| root_fn());
838    let width = config.width as f32;
839    let height = config.height as f32;
840    let dpr = android_window.scale_factor();
841    let mut runtime = AppRuntime::new(view, width, height, dpr);
842    runtime.apply_window_config(&config);
843    let presenter =
844        SoftwareSurfacePresenter::new(config.width, config.height, SwapchainFormat::Bgra8Unorm);
845    let compositor = SwapchainCompositor::new(config.width, config.height, dpr);
846
847    run_native_surface_window_loop(
848        android_window,
849        Some(root_fn),
850        runtime,
851        compositor,
852        presenter,
853        event_handler,
854        None,
855    )
856}
857
858#[cfg(target_os = "ios")]
859/// Launches an interactive native iOS application window via UIKit and CAMetalLayer.
860pub fn launch_ios<F>(root_fn: F, config: WindowConfig) -> Result<(), String>
861where
862    F: FnMut() -> View + 'static,
863{
864    launch_ios_with_events(root_fn, config, |_, _| false)
865}
866
867#[cfg(target_os = "ios")]
868/// Launches an interactive native iOS application window with a custom event hook.
869pub fn launch_ios_with_events<F, E>(
870    mut root_fn: F,
871    config: WindowConfig,
872    event_handler: E,
873) -> Result<(), String>
874where
875    F: FnMut() -> View + 'static,
876    E: FnMut(&strata_platform::PlatformEvent, &mut AppRuntime) -> bool + 'static,
877{
878    let ios_window = strata_platform::IosWindow::new(config.clone())?;
879    let view = strata_dom::with_root_component_scope(|| root_fn());
880    let width = config.width as f32;
881    let height = config.height as f32;
882    let dpr = ios_window.scale_factor();
883    let mut runtime = AppRuntime::new(view, width, height, dpr);
884    runtime.apply_window_config(&config);
885    let presenter =
886        SoftwareSurfacePresenter::new(config.width, config.height, SwapchainFormat::Bgra8Unorm);
887    let compositor = SwapchainCompositor::new(config.width, config.height, dpr);
888
889    run_native_surface_window_loop(
890        ios_window,
891        Some(root_fn),
892        runtime,
893        compositor,
894        presenter,
895        event_handler,
896        None,
897    )
898}