Skip to main content

strata/runtime/
mod.rs

1//! Live Application Runtime Orchestrator connecting RSX Blueprints, Style Cascade, Layout, and Rendering.
2
3use strata_dom::{NodeBlueprint, Tag, View};
4use strata_layout::prelude::*;
5use strata_platform::{
6    EventLoop, EventLoopControl, LivePlatformWindow, NativeSurfaceWindow, PlatformEvent,
7    PlatformWindow, SoftwareSurfacePresenter, SwapchainCompositor, SwapchainFormat, WindowConfig,
8};
9use strata_render::compositor::DisplayList;
10use strata_render::swapchain::{PresentError, SurfacePresenter};
11use strata_style::types::{ComputedStyle, Dimension, Display, FlexDirection};
12
13pub mod app;
14pub mod edit;
15pub mod launch;
16pub mod platforms;
17pub mod types;
18
19mod a11y;
20mod animation;
21mod canvas3d;
22pub mod dom_hydration;
23mod events;
24mod hit_test;
25mod hover;
26mod image;
27mod input_hit_test;
28mod layout_tree;
29mod mcp;
30mod profile;
31mod scroll;
32mod scrollbar;
33mod selection;
34pub mod spatial;
35mod tailwind;
36pub mod test_support;
37
38pub use app::*;
39pub use dom_hydration::*;
40pub use edit::*;
41pub(crate) use image::*;
42pub use launch::*;
43pub use platforms::*;
44pub use profile::{FrameProfile, FrameProfileHook};
45pub use spatial::*;
46pub use test_support::{MatchMode, NodeQuery};
47pub use types::*;
48
49/// Live running application instance holding active state, layout tree, and display list.
50#[derive(Debug)]
51pub struct AppRuntime {
52    pub root_blueprint: NodeBlueprint,
53    pub ir_graph: strata_dom::UiIrGraph,
54    pub layout_root: LayoutNode,
55    pub display_list: DisplayList,
56    pub spatial_index: SpatialIndex,
57    pub viewport_width: f32,
58    pub viewport_height: f32,
59    pub dpr: f32,
60    pub frame_count: u64,
61    pub active_focus: Option<ActiveInput>,
62    pub input_states: std::collections::HashMap<String, strata_dom::text_input::TextInputState>,
63    pub caret_blink_epoch: std::time::Instant,
64    pub last_caret_blink_state: bool,
65    pub current_cursor: strata_platform::window::CursorIcon,
66    pub drag_selection_active: bool,
67    pub last_click_info: Option<(std::time::Instant, f32, f32, usize)>,
68    /// Press origin of a possible window drag started on a `data-app-region="drag"` surface.
69    pub pending_window_drag: Option<(f32, f32)>,
70    /// Time and position of the previous drag-region press, for double-click maximize toggling.
71    pub last_drag_click: Option<(std::time::Instant, f32, f32)>,
72    /// Hierarchical index path of the currently hovered element node.
73    pub current_hover_path: Option<Vec<usize>>,
74    /// Hierarchical index path of the currently focused element node.
75    pub current_focus_path: Option<Vec<usize>>,
76    /// Whether pointer primary button is currently held down.
77    pub is_mouse_down: bool,
78    /// Whether dark mode is active for theme-dependent utility styling.
79    pub is_dark_mode: bool,
80    /// Last recorded pointer coordinates.
81    pub last_mouse_pos: (f32, f32),
82    /// Resolved native tooltip text (`title` or button/image `alt`) for the hovered element.
83    pub hover_tooltip_text: Option<String>,
84    /// Tree path of the element that owns `hover_tooltip_text`.
85    pub hover_tooltip_path: Option<Vec<usize>>,
86    /// Pointer coordinates used to anchor the native hover tooltip.
87    pub hover_tooltip_anchor: (f32, f32),
88    /// Timestamp when pointer dwell began on the current tooltip target.
89    pub hover_tooltip_since: Option<std::time::Instant>,
90    /// Whether the native hover tooltip popup is currently displayed.
91    pub hover_tooltip_visible: bool,
92    /// Dwell delay before a native hover tooltip becomes visible.
93    pub hover_tooltip_delay: std::time::Duration,
94    /// Visual styling and offset configuration for native hover tooltips.
95    pub hover_tooltip_style: strata_platform::HoverTooltipStyle,
96    /// Scroll offsets keyed by hierarchical tree path (e.g. [0, 1, 0]).
97    pub scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
98    /// Scroll offsets keyed by element string ID (e.g. "browser-viewport-tab-1").
99    pub scroll_offsets_by_id: std::collections::HashMap<String, (f32, f32)>,
100    /// Active scrollbars currently visible on screen.
101    pub active_scrollbars: Vec<ActiveScrollbar>,
102    /// Active drag operation on a scrollbar thumb.
103    pub scrollbar_drag: Option<ScrollbarDrag>,
104    /// Active kinetic smooth scroll animation tracker.
105    pub active_smooth_scroll: Option<SmoothScrollTracker>,
106    /// Timestamp of the last scroll interaction (for animated scrollbar thumb fade).
107    pub last_scroll_interaction: Option<std::time::Instant>,
108    /// Scroll offsets currently applied via translation to the layout tree, keyed by hierarchical tree path.
109    pub applied_scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
110    /// Anchored top-layer `<Portal>` translations currently applied to the layout tree, keyed by path.
111    pub applied_portal_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
112    /// Cached flag indicating whether the active layout tree contains any anchored `<Portal>` nodes.
113    pub(crate) has_anchored_portals: bool,
114    /// Continuous presentation epoch for animation and transition timing.
115    pub runtime_start_epoch: std::time::Instant,
116    /// Coordinator for CSS transition properties across elements.
117    pub transition_manager: strata_style::transition::TransitionManager,
118    /// Coordinator for CSS keyframe animations across elements.
119    pub animation_manager: strata_style::animation::AnimationManager,
120    /// Base un-animated computed styles for all layout tree nodes keyed by deterministic node ID.
121    pub base_node_styles: std::collections::HashMap<u64, ComputedStyle>,
122    /// Previous frame's computed styles for transition diffing.
123    pub previous_node_styles: std::collections::HashMap<u64, ComputedStyle>,
124    /// Mapping from deterministic node ID to its hierarchical tree path.
125    pub node_paths: std::collections::HashMap<u64, Vec<usize>>,
126    /// Mapping from hierarchical tree path to its identity-aware animation node ID.
127    pub path_node_ids: std::collections::HashMap<Vec<usize>, u64>,
128    /// Coordinator for CSS View Transitions Module snapshots and element morphing.
129    pub view_transition_manager: crate::view_transition::ViewTransitionManager,
130    /// Whether animations or transitions were active in the prior frame (to allow clean final state settlement).
131    pub had_active_animations: bool,
132    /// Hardware GPU path compilation pipeline for direct compute shader execution.
133    pub gpu_path_pipeline: strata_render::GpuPathPipeline,
134    /// Number of full layout computations performed by this runtime (test/profiling hook).
135    pub(crate) layout_computations: u64,
136    /// True when the most recent hover transition only needed a paint refresh.
137    pub(crate) hover_paint_only: bool,
138    /// Active MCP emulated cursor state (smooth interpolation, hotspot, fade timer).
139    pub mcp_cursor: Option<strata_platform::McpCursorState>,
140    /// System cursor theme loaded dynamically or from embedded fallback assets (Yaru on Linux).
141    pub(crate) cursor_theme: std::sync::OnceLock<strata_platform::CursorTheme>,
142    /// Accessibility tree bridge connecting Strata layout and reactive DOM with AccessKit and screen readers.
143    pub a11y_bridge: strata_a11y::A11yBridge,
144    /// Latest snapshot of the accessible hierarchy.
145    pub a11y_tree: Option<strata_a11y::A11yTree>,
146    /// Number of accessibility tree synchronizations performed.
147    pub a11y_updates_count: u64,
148    /// Fine-grained dynamic text bindings mapped directly to layout node paths.
149    pub dynamic_text_bindings: Vec<DynamicTextBinding>,
150    /// Background channel receiver for live DOM mutations from scripts or browser tabs.
151    pub dom_mutation_receiver: Option<std::sync::mpsc::Receiver<strata_js::DomMutationRecord>>,
152    #[cfg(feature = "devtools")]
153    /// Integrated DevTools diagnostics suite (HUD, Profiler, Heap Tracker, CDP).
154    pub devtools: Option<strata_devtools::DevTools>,
155    /// Client-Side Decorations (CSD) controller managing titlebar geometry and drag tracking.
156    pub csd_controller: strata_platform::CsdController,
157    /// Phase timings accumulated since the last presented frame.
158    pub(crate) frame_profile: FrameProfile,
159    /// True when anything that affects painting changed since the display list was compiled.
160    pub(crate) paint_dirty: bool,
161    /// True when only retained 3D state changed without invalidating 2D layout or display list.
162    pub(crate) viewport_3d_dirty: bool,
163    /// Retained 3D scene handles in the compiled display list paired with last presented generations.
164    pub(crate) tracked_retained_3d: Vec<(strata_render::scene3d::RetainedScene3D, (u64, u64, u64))>,
165    /// Number of display-list compilations skipped because nothing changed.
166    pub(crate) compiles_skipped: u64,
167    /// Optional observer invoked with the completed profile after each present.
168    pub(crate) frame_profile_hook: Option<FrameProfileHook>,
169    /// Cached `<style>` stylesheets collected from `root_blueprint`.
170    pub(crate) cached_stylesheets: Vec<std::sync::Arc<strata_style::StyleSheet>>,
171    /// Active pointer capture or drag target `(tree_path, explicit_capture)`.
172    pub pointer_capture_target: Option<(Vec<usize>, bool)>,
173    /// True when the current `root_blueprint` contains any `EventType::Resize` listeners.
174    pub(crate) has_resize_listeners: bool,
175    /// Last observed `(width, height)` for elements with `onresize` listeners, keyed by node ID.
176    pub observed_element_sizes: std::collections::HashMap<u64, (f32, f32)>,
177    /// Last pointer position `(x, y)` for computing `movement_x` / `movement_y`.
178    pub(crate) last_pointer_pos: Option<(f32, f32)>,
179    /// Target `(x, y)` of an in-flight cursor warp so synthetic warp deltas are filtered.
180    pub(crate) pending_cursor_warp: Option<(f32, f32)>,
181    /// True when the most recent `update_view` call reconciled the existing layout tree in place.
182    pub(crate) last_update_reconciled: bool,
183    /// Active native DOM drag-and-drop operation (`ondragstart`, `ondragover`, `ondrop`, etc.).
184    pub(crate) active_dom_drag: Option<ActiveDomDrag>,
185}
186
187/// Whether opt-in `[perf]` timing output is enabled through `STRATA_PERF_LOG`.
188pub(crate) fn perf_logging_enabled() -> bool {
189    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
190    *ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
191}
192
193/// Emits a gated duration measurement for the `[perf]` diagnostic channel.
194pub(crate) fn perf_log_ms(label: &str, start: std::time::Instant, detail: impl std::fmt::Display) {
195    if perf_logging_enabled() {
196        eprintln!(
197            "[perf] {}: {:.3} ms ({})",
198            label,
199            start.elapsed().as_secs_f64() * 1000.0,
200            detail
201        );
202    }
203}
204
205pub(crate) fn perf_count_layout_nodes(node: &strata_layout::LayoutNode) -> usize {
206    let mut count = 0;
207    let mut stack = vec![node];
208    while let Some(n) = stack.pop() {
209        count += 1;
210        for child in &n.children {
211            stack.push(child);
212        }
213    }
214    count
215}
216
217pub(crate) fn perf_count_blueprint_nodes(node: &NodeBlueprint) -> usize {
218    let mut count = 0;
219    let mut stack = vec![node];
220    while let Some(n) = stack.pop() {
221        count += 1;
222        match n {
223            NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
224                for child in children {
225                    stack.push(child);
226                }
227            }
228            NodeBlueprint::Text(_) | NodeBlueprint::DynamicText(_) | NodeBlueprint::Empty => {}
229        }
230    }
231    count
232}
233
234impl AppRuntime {
235    /// Builds a root [`View`] inside an implicit root component scope (when no outer `#[component]`
236    /// scope is active) and mounts a new [`AppRuntime`].
237    ///
238    /// Prefer this over [`Self::new`] when rendering plain closures containing unkeyed top-level
239    /// sibling components (`|| rsx! { <> <Child /> <Child /> </> }`) so siblings receive distinct
240    /// hook slots and run `use_effect` unmount cleanups when toggled off.
241    pub fn from_root<F: FnOnce() -> View>(
242        root: F,
243        viewport_width: f32,
244        viewport_height: f32,
245        dpr: f32,
246    ) -> Self {
247        let root_view = strata_dom::with_root_component_scope(root);
248        Self::new(root_view, viewport_width, viewport_height, dpr)
249    }
250
251    /// Creates and mounts a new application runtime from a root view.
252    pub fn new(root_view: View, viewport_width: f32, viewport_height: f32, dpr: f32) -> Self {
253        #[cfg(target_os = "linux")]
254        strata_platform::init_pango_text_measurement();
255
256        let mut root_blueprint = root_view.root.flatten_fragments();
257        root_blueprint.ensure_entity_ids();
258        let mut ir_graph = Self::build_ir_graph(&root_blueprint);
259
260        let build_start = std::time::Instant::now();
261        let mut layout_root = Self::build_layout_tree(&root_blueprint);
262        if perf_logging_enabled() {
263            perf_log_ms(
264                "build_layout_tree_initial",
265                build_start,
266                format!("{} layout nodes", perf_count_layout_nodes(&layout_root)),
267            );
268        }
269
270        let compute_start = std::time::Instant::now();
271        layout_root.compute_layout(viewport_width, viewport_height);
272        Self::sync_layout_to_ir(&layout_root, &mut ir_graph);
273        let mut spatial_index = SpatialIndex::new();
274        spatial_index.rebuild(&root_blueprint, &layout_root);
275        if perf_logging_enabled() {
276            perf_log_ms(
277                "compute_layout_initial",
278                compute_start,
279                format!("{}x{}", viewport_width, viewport_height),
280            );
281        }
282
283        let mut dynamic_text_bindings = Vec::new();
284        let mut path_buf = Vec::new();
285        Self::collect_dynamic_text_bindings(
286            &root_blueprint,
287            &mut path_buf,
288            &mut dynamic_text_bindings,
289        );
290
291        let mut runtime = Self {
292            root_blueprint,
293            ir_graph,
294            layout_root,
295            display_list: DisplayList::new(),
296            spatial_index,
297            viewport_width,
298            viewport_height,
299            dpr,
300            frame_count: 0,
301            active_focus: None,
302            input_states: std::collections::HashMap::new(),
303            caret_blink_epoch: std::time::Instant::now(),
304            last_caret_blink_state: true,
305            current_cursor: strata_platform::window::CursorIcon::Default,
306            drag_selection_active: false,
307            last_click_info: None,
308            pending_window_drag: None,
309            last_drag_click: None,
310            current_hover_path: None,
311            current_focus_path: None,
312            is_mouse_down: false,
313            is_dark_mode: false,
314            last_mouse_pos: (0.0, 0.0),
315            hover_tooltip_text: None,
316            hover_tooltip_path: None,
317            hover_tooltip_anchor: (0.0, 0.0),
318            hover_tooltip_since: None,
319            hover_tooltip_visible: false,
320            hover_tooltip_delay: std::time::Duration::from_millis(450),
321            hover_tooltip_style: strata_platform::HoverTooltipStyle::default(),
322            scroll_offsets: std::collections::HashMap::new(),
323            scroll_offsets_by_id: std::collections::HashMap::new(),
324            active_scrollbars: Vec::new(),
325            scrollbar_drag: None,
326            active_smooth_scroll: None,
327            last_scroll_interaction: None,
328            applied_scroll_offsets: std::collections::HashMap::new(),
329            applied_portal_offsets: std::collections::HashMap::new(),
330            has_anchored_portals: false,
331            runtime_start_epoch: std::time::Instant::now(),
332            transition_manager: strata_style::transition::TransitionManager::new(),
333            animation_manager: strata_style::animation::AnimationManager::new(),
334            base_node_styles: std::collections::HashMap::new(),
335            previous_node_styles: std::collections::HashMap::new(),
336            node_paths: std::collections::HashMap::new(),
337            path_node_ids: std::collections::HashMap::new(),
338            view_transition_manager: crate::view_transition::ViewTransitionManager::new(),
339            had_active_animations: false,
340            gpu_path_pipeline: strata_render::GpuPathPipeline::new(viewport_width, viewport_height),
341            layout_computations: 1,
342            hover_paint_only: false,
343            mcp_cursor: None,
344            cursor_theme: std::sync::OnceLock::new(),
345            a11y_bridge: strata_a11y::A11yBridge::new(),
346            a11y_tree: None,
347            a11y_updates_count: 0,
348            dynamic_text_bindings,
349            dom_mutation_receiver: None,
350            #[cfg(feature = "devtools")]
351            devtools: None,
352            csd_controller: strata_platform::CsdController::default(),
353            frame_profile: FrameProfile::default(),
354            paint_dirty: true,
355            viewport_3d_dirty: false,
356            tracked_retained_3d: Vec::new(),
357            compiles_skipped: 0,
358            frame_profile_hook: None,
359            cached_stylesheets: Vec::new(),
360            pointer_capture_target: None,
361            has_resize_listeners: false,
362            observed_element_sizes: std::collections::HashMap::new(),
363            last_pointer_pos: None,
364            pending_cursor_warp: None,
365            last_update_reconciled: false,
366            active_dom_drag: None,
367        };
368
369        runtime.has_resize_listeners =
370            Self::blueprint_has_resize_listeners(&runtime.root_blueprint);
371        let initial_sheets = Self::collect_stylesheets_from_blueprint(&runtime.root_blueprint);
372        for sheet in &initial_sheets {
373            runtime.register_keyframes_stylesheet(sheet);
374        }
375        runtime.cached_stylesheets = initial_sheets;
376        runtime.sync_tree_animations(0.0);
377        runtime.apply_viewport_clamps();
378        runtime.apply_scroll_offsets();
379        runtime.dispatch_resize_observers();
380        runtime
381            .spatial_index
382            .rebuild(&runtime.root_blueprint, &runtime.layout_root);
383        runtime.update_accessibility_tree();
384        runtime.compile_display_list();
385        runtime
386    }
387
388    /// Applies runtime-relevant preferences from a [`WindowConfig`] (such as native hover
389    /// tooltip dwell delay and styling).
390    pub fn apply_window_config(&mut self, config: &WindowConfig) -> &mut Self {
391        self.hover_tooltip_delay = config.tooltip_delay;
392        self.hover_tooltip_style = config.tooltip_style;
393        if self.hover_tooltip_visible {
394            self.paint_dirty = true;
395        }
396        self
397    }
398
399    /// Sets the pointer dwell delay before native hover tooltips (`title` / `alt`) become visible.
400    pub fn set_hover_tooltip_delay(&mut self, delay: std::time::Duration) -> &mut Self {
401        self.hover_tooltip_delay = delay;
402        self
403    }
404
405    /// Sets the pointer dwell delay in milliseconds before native hover tooltips become visible.
406    pub fn set_hover_tooltip_delay_ms(&mut self, delay_ms: u64) -> &mut Self {
407        self.hover_tooltip_delay = std::time::Duration::from_millis(delay_ms);
408        self
409    }
410
411    /// Returns the configured pointer dwell delay for native hover tooltips.
412    pub fn hover_tooltip_delay(&self) -> std::time::Duration {
413        self.hover_tooltip_delay
414    }
415
416    /// Sets visual styling and offset configuration for native hover tooltips.
417    pub fn set_hover_tooltip_style(
418        &mut self,
419        style: strata_platform::HoverTooltipStyle,
420    ) -> &mut Self {
421        self.hover_tooltip_style = style;
422        if self.hover_tooltip_visible {
423            self.paint_dirty = true;
424        }
425        self
426    }
427
428    /// Returns the active visual styling configuration for native hover tooltips.
429    pub fn hover_tooltip_style(&self) -> strata_platform::HoverTooltipStyle {
430        self.hover_tooltip_style
431    }
432
433    /// Re-evaluates layout and compiles display commands for the current frame.
434    pub fn tick_frame(&mut self) -> &DisplayList {
435        self.frame_count += 1;
436        self.unapply_scroll_offsets();
437        let compute_start = std::time::Instant::now();
438        self.layout_root
439            .compute_layout(self.viewport_width, self.viewport_height);
440        Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
441        self.layout_computations += 1;
442        self.frame_profile.layout += compute_start.elapsed();
443        if perf_logging_enabled() {
444            perf_log_ms(
445                "compute_layout_tick",
446                compute_start,
447                format!(
448                    "{} layout nodes",
449                    perf_count_layout_nodes(&self.layout_root)
450                ),
451            );
452        }
453        self.apply_viewport_clamps();
454        self.apply_scroll_offsets();
455        self.sync_active_input_layout();
456        self.dispatch_resize_observers();
457        self.spatial_index
458            .rebuild(&self.root_blueprint, &self.layout_root);
459        self.update_accessibility_tree();
460        self.compile_display_list();
461        &self.display_list
462    }
463
464    /// Returns the current interaction context.
465    pub fn interaction_context(&self) -> InteractionContext<'_> {
466        InteractionContext {
467            hovered_path: self.current_hover_path.as_deref(),
468            focused_path: self.current_focus_path.as_deref(),
469            is_mouse_down: self.is_mouse_down,
470            is_dark_mode: self.is_dark_mode,
471        }
472    }
473
474    /// Sets the active dark mode state and triggers a layout and style recomputation if changed.
475    pub fn set_dark_mode(&mut self, is_dark: bool) -> bool {
476        if self.is_dark_mode != is_dark {
477            self.is_dark_mode = is_dark;
478            self.rebuild_layout_tree();
479            true
480        } else {
481            false
482        }
483    }
484
485    /// Sets the active focused element path and triggers a layout and style recomputation if changed.
486    pub fn set_focus_path(&mut self, path: Option<Vec<usize>>) -> bool {
487        if self.current_focus_path != path {
488            self.current_focus_path = path;
489            self.rebuild_layout_tree();
490            true
491        } else {
492            false
493        }
494    }
495
496    /// Clears and rebuilds the spatial acceleration index.
497    pub fn rebuild_spatial_index(&mut self) {
498        self.spatial_index
499            .rebuild(&self.root_blueprint, &self.layout_root);
500    }
501
502    /// Queries the front-most EntityId at point (px, py).
503    pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<strata_primitives::EntityId> {
504        self.spatial_index.query_entity_at_point(px, py)
505    }
506
507    /// Queries the front-most event listener registered for `event_type` at point (px, py).
508    pub fn query_event_at_point(
509        &self,
510        px: f32,
511        py: f32,
512        event_type: strata_dom::EventType,
513    ) -> Option<(
514        strata_primitives::EntityId,
515        std::rc::Rc<dyn Fn(strata_dom::Event)>,
516        strata_layout::Rect,
517    )> {
518        self.spatial_index.query_event_at_point(px, py, event_type)
519    }
520
521    /// Recursively locates a layout node by its EntityId.
522    pub fn find_layout_by_entity(
523        &self,
524        entity_id: strata_primitives::EntityId,
525    ) -> Option<&LayoutNode> {
526        self.layout_root.find_by_entity_id(entity_id)
527    }
528
529    /// Recursively locates a mutable layout node by its EntityId.
530    pub fn find_layout_mut_by_entity(
531        &mut self,
532        entity_id: strata_primitives::EntityId,
533    ) -> Option<&mut LayoutNode> {
534        self.layout_root.find_by_entity_id_mut(entity_id)
535    }
536
537    /// Recursively locates a blueprint node by its EntityId.
538    pub fn find_blueprint_by_entity(
539        &self,
540        entity_id: strata_primitives::EntityId,
541    ) -> Option<&NodeBlueprint> {
542        self.root_blueprint.find_by_entity_id(entity_id)
543    }
544
545    /// Queries the laid-out border-box rectangle `(x, y, width, height)` for an element by `id`.
546    pub fn query_element_rect(&self, element_id: &str) -> Option<strata_layout::Rect> {
547        fn find_rec(node: &LayoutNode, target_id: &str) -> Option<strata_layout::Rect> {
548            if node.element_id.as_deref() == Some(target_id) {
549                return Some(node.geometry.border_box);
550            }
551            for child in &node.children {
552                if let Some(rect) = find_rec(child, target_id) {
553                    return Some(rect);
554                }
555            }
556            None
557        }
558        find_rec(&self.layout_root, element_id)
559    }
560
561    /// Warps the OS pointer to window-local `(x, y)` and records the target so the
562    /// resulting synthetic motion delta is filtered from `movement_x` / `movement_y`.
563    pub fn warp_cursor(&mut self, x: f32, y: f32) {
564        self.last_pointer_pos = Some((x, y));
565        self.pending_cursor_warp = Some((x, y));
566        #[cfg(target_os = "linux")]
567        strata_platform::gtk_warp_cursor(x as f64, y as f64);
568    }
569
570    /// Alias for [`AppRuntime::warp_cursor`].
571    pub fn set_cursor_position(&mut self, x: f32, y: f32) {
572        self.warp_cursor(x, y);
573    }
574
575    /// Updates `flex_grow`, `flex_shrink`, and optional `flex_basis` on the layout node
576    /// matching `element_id` in-place, invalidating only its ancestor chain's layout cache.
577    pub fn update_element_flex(
578        &mut self,
579        element_id: &str,
580        flex_grow: f32,
581        flex_shrink: f32,
582        flex_basis: Option<strata_style::types::Dimension>,
583    ) -> bool {
584        fn update_rec(
585            node: &mut LayoutNode,
586            target_id: &str,
587            flex_grow: f32,
588            flex_shrink: f32,
589            flex_basis: Option<strata_style::types::Dimension>,
590        ) -> bool {
591            if node.element_id.as_deref() == Some(target_id) {
592                node.style.flex_grow = flex_grow;
593                node.style.flex_shrink = flex_shrink;
594                if let Some(basis) = flex_basis {
595                    node.style.flex_basis = basis;
596                }
597                node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
598                return true;
599            }
600            let mut changed = false;
601            for child in &mut node.children {
602                if update_rec(child, target_id, flex_grow, flex_shrink, flex_basis) {
603                    changed = true;
604                }
605            }
606            if changed {
607                node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
608            }
609            changed
610        }
611        update_rec(
612            &mut self.layout_root,
613            element_id,
614            flex_grow,
615            flex_shrink,
616            flex_basis,
617        )
618    }
619
620    /// Updates `flex_grow` ratios for multiple `element_id`s in-place and runs an isolated
621    /// layout-only pass without rebuilding the DOM, stylesheets, or IR graph.
622    pub fn update_split_ratios(&mut self, updates: &[(&str, f32)]) -> bool {
623        let mut any_changed = false;
624        for &(id, ratio) in updates {
625            if self.update_element_flex(id, ratio, 1.0, None) {
626                any_changed = true;
627            }
628        }
629        if any_changed {
630            self.relayout_in_place();
631        }
632        any_changed
633    }
634
635    /// Recomputes layout, scroll/viewport clamps, resize observers, spatial index, and
636    /// display list in-place without rebuilding `layout_root` or `ir_graph`.
637    pub fn relayout_in_place(&mut self) {
638        self.unapply_scroll_offsets();
639        let compute_start = std::time::Instant::now();
640        self.layout_root
641            .compute_layout(self.viewport_width, self.viewport_height);
642        self.layout_computations += 1;
643        self.frame_profile.layout += compute_start.elapsed();
644        self.apply_viewport_clamps();
645        self.apply_scroll_offsets();
646        self.dispatch_resize_observers();
647        self.spatial_index
648            .rebuild(&self.root_blueprint, &self.layout_root);
649        self.paint_dirty = true;
650        self.compile_display_list();
651    }
652
653    /// Returns true if any element in `bp` registers an `EventType::Resize` listener.
654    pub(crate) fn blueprint_has_resize_listeners(bp: &NodeBlueprint) -> bool {
655        match bp {
656            NodeBlueprint::Element {
657                attributes,
658                children,
659                ..
660            } => {
661                attributes.iter().any(|a| {
662                    matches!(
663                        a,
664                        strata_dom::Attribute::EventListener {
665                            event: strata_dom::EventType::Resize,
666                            ..
667                        }
668                    )
669                }) || children.iter().any(Self::blueprint_has_resize_listeners)
670            }
671            NodeBlueprint::Fragment(children) => {
672                children.iter().any(Self::blueprint_has_resize_listeners)
673            }
674            _ => false,
675        }
676    }
677
678    /// Dispatches `EventType::Resize` (`onresize`) callbacks for any element whose laid-out
679    /// `(width, height)` changed since the last observation. Returns `true` if any callback fired.
680    pub fn dispatch_resize_observers(&mut self) -> bool {
681        if !self.has_resize_listeners {
682            return false;
683        }
684        let mut pending: Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)> =
685            Vec::new();
686        let mut active_ids = std::collections::HashSet::new();
687        let mut path = Vec::new();
688
689        #[allow(clippy::too_many_arguments)]
690        fn collect_rec(
691            bp: &NodeBlueprint,
692            layout: &LayoutNode,
693            path: &mut Vec<usize>,
694            path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
695            observed: &mut std::collections::HashMap<u64, (f32, f32)>,
696            active_ids: &mut std::collections::HashSet<u64>,
697            pending: &mut Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)>,
698        ) {
699            if let NodeBlueprint::Element {
700                attributes,
701                children,
702                ..
703            } = bp
704            {
705                let node_id = path_node_ids
706                    .get(path)
707                    .copied()
708                    .unwrap_or_else(|| path_to_node_id(path));
709                let mut resize_handlers = Vec::new();
710                for attr in attributes {
711                    if let strata_dom::Attribute::EventListener {
712                        event: strata_dom::EventType::Resize,
713                        handler,
714                    } = attr
715                    {
716                        resize_handlers.push(handler.clone());
717                    }
718                }
719                if !resize_handlers.is_empty() {
720                    active_ids.insert(node_id);
721                    let w = layout.geometry.border_box.width;
722                    let h = layout.geometry.border_box.height;
723                    let changed = match observed.get(&node_id) {
724                        Some(&(pw, ph)) => (w - pw).abs() > 0.25 || (h - ph).abs() > 0.25,
725                        None => true,
726                    };
727                    if changed {
728                        observed.insert(node_id, (w, h));
729                        for handler in resize_handlers {
730                            pending.push((handler, layout.geometry.border_box));
731                        }
732                    }
733                }
734                for (idx, child_layout) in layout.children.iter().enumerate() {
735                    if let Some(child_bp) = children.get(idx) {
736                        path.push(idx);
737                        collect_rec(
738                            child_bp,
739                            child_layout,
740                            path,
741                            path_node_ids,
742                            observed,
743                            active_ids,
744                            pending,
745                        );
746                        path.pop();
747                    }
748                }
749            }
750        }
751
752        collect_rec(
753            &self.root_blueprint,
754            &self.layout_root,
755            &mut path,
756            &self.path_node_ids,
757            &mut self.observed_element_sizes,
758            &mut active_ids,
759            &mut pending,
760        );
761        self.observed_element_sizes
762            .retain(|id, _| active_ids.contains(id));
763
764        if pending.is_empty() {
765            return false;
766        }
767        for (handler, rect) in pending {
768            let mut ev = strata_dom::Event::new(strata_dom::EventType::Resize);
769            ev.client_x = rect.x as f64;
770            ev.client_y = rect.y as f64;
771            ev.offset_x = rect.width as f64;
772            ev.offset_y = rect.height as f64;
773            ev.width = rect.width as f64;
774            ev.height = rect.height as f64;
775            handler(ev);
776        }
777        true
778    }
779
780    fn element_attr_value<'a>(
781        attrs: &'a [strata_dom::Attribute],
782        key_name: &str,
783    ) -> Option<&'a str> {
784        attrs.iter().find_map(|a| match a {
785            strata_dom::Attribute::Property { key, value } if key == key_name => {
786                Some(value.as_str())
787            }
788            _ => None,
789        })
790    }
791
792    fn attributes_visually_equal(a: &[strata_dom::Attribute], b: &[strata_dom::Attribute]) -> bool {
793        let mut iter_a = a.iter().filter(|attr| {
794            !matches!(
795                attr,
796                strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
797            )
798        });
799        let mut iter_b = b.iter().filter(|attr| {
800            !matches!(
801                attr,
802                strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
803            )
804        });
805        loop {
806            match (iter_a.next(), iter_b.next()) {
807                (None, None) => return true,
808                (Some(x), Some(y)) => match (x, y) {
809                    (
810                        strata_dom::Attribute::Property { key: k1, value: v1 },
811                        strata_dom::Attribute::Property { key: k2, value: v2 },
812                    ) if k1 == k2 && v1 == v2 => {}
813                    (
814                        strata_dom::Attribute::DirectStyle(d1),
815                        strata_dom::Attribute::DirectStyle(d2),
816                    ) if std::rc::Rc::ptr_eq(d1, d2) => {}
817                    (
818                        strata_dom::Attribute::ScenePayload(s1),
819                        strata_dom::Attribute::ScenePayload(s2),
820                    ) if std::sync::Arc::ptr_eq(s1, s2) => {}
821                    _ => return false,
822                },
823                _ => return false,
824            }
825        }
826    }
827
828    fn inherited_style_equal(
829        a: &strata_style::ComputedStyle,
830        b: &strata_style::ComputedStyle,
831    ) -> bool {
832        a.color == b.color
833            && a.font_family == b.font_family
834            && a.font_size == b.font_size
835            && a.root_font_size == b.root_font_size
836            && a.font_weight == b.font_weight
837            && a.font_style == b.font_style
838            && a.text_align == b.text_align
839            && a.line_height == b.line_height
840            && a.letter_spacing == b.letter_spacing
841            && a.text_decoration == b.text_decoration
842            && a.text_transform == b.text_transform
843            && a.text_overflow == b.text_overflow
844            && a.white_space == b.white_space
845            && a.cursor == b.cursor
846            && a.user_select == b.user_select
847            && a.pointer_events == b.pointer_events
848            && a.visibility == b.visibility
849            && a.caret_color == b.caret_color
850            && a.border_collapse == b.border_collapse
851            && a.border_spacing == b.border_spacing
852            && a.caption_side == b.caption_side
853            && a.custom_properties == b.custom_properties
854    }
855
856    fn blueprint_visually_equal(a: &NodeBlueprint, b: &NodeBlueprint) -> bool {
857        match (a, b) {
858            (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => t1 == t2,
859            (NodeBlueprint::Empty, NodeBlueprint::Empty) => true,
860            (
861                NodeBlueprint::Element {
862                    tag: t1,
863                    classes: cls1,
864                    attributes: a1,
865                    children: c1,
866                },
867                NodeBlueprint::Element {
868                    tag: t2,
869                    classes: cls2,
870                    attributes: a2,
871                    children: c2,
872                },
873            ) => {
874                t1 == t2
875                    && cls1 == cls2
876                    && c1.len() == c2.len()
877                    && Self::attributes_visually_equal(a1, a2)
878                    && c1
879                        .iter()
880                        .zip(c2.iter())
881                        .all(|(x, y)| Self::blueprint_visually_equal(x, y))
882            }
883            _ => false,
884        }
885    }
886
887    /// Reconciles `layout_node` in-place from `old_bp` to `new_bp`, preserving W3C CSS property
888    /// inheritance top-down from `parent_style`.
889    /// Returns `None` if a structural mismatch requires a full subtree rebuild,
890    /// `Some(true)` if any layout cache in this subtree was invalidated, or
891    /// `Some(false)` if this entire subtree is visually and structurally identical.
892    fn reconcile_layout_subtree(
893        old_bp: &NodeBlueprint,
894        new_bp: &NodeBlueprint,
895        layout_node: &mut LayoutNode,
896        parent_style: Option<&strata_style::ComputedStyle>,
897        parent_inherited_changed: bool,
898        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
899        ctx: &crate::runtime::InteractionContext,
900    ) -> Option<bool> {
901        match (old_bp, new_bp) {
902            (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => {
903                if t1 == t2 && !parent_inherited_changed {
904                    Some(false)
905                } else {
906                    *layout_node = Self::build_text_leaf_layout_node(t2.clone(), parent_style);
907                    Some(true)
908                }
909            }
910            (
911                NodeBlueprint::Element { tag: t1, .. },
912                NodeBlueprint::Element { tag: t2, .. },
913            ) if t1 == t2
914                && matches!(
915                    t1,
916                    strata_dom::Tag::Svg
917                        | strata_dom::Tag::Path
918                        | strata_dom::Tag::Input
919                        | strata_dom::Tag::Img
920                ) =>
921            {
922                if !parent_inherited_changed && Self::blueprint_visually_equal(old_bp, new_bp) {
923                    if let Some(eid) = new_bp.entity_id() {
924                        layout_node.entity_id = eid;
925                    }
926                    Some(false)
927                } else {
928                    None
929                }
930            }
931            (
932                NodeBlueprint::Element {
933                    tag: t1,
934                    classes: cls1,
935                    attributes: a1,
936                    children: c1,
937                },
938                NodeBlueprint::Element {
939                    tag: t2,
940                    classes: cls2,
941                    attributes: a2,
942                    children: c2,
943                },
944            ) if t1 == t2
945                && !layout_node.is_top_layer
946                && layout_node.children.len() == c1.len()
947                && Self::element_attr_value(a1, "key") == Self::element_attr_value(a2, "key")
948                && Self::element_attr_value(a1, "id") == Self::element_attr_value(a2, "id") =>
949            {
950                let self_props_changed = cls1 != cls2 || !Self::attributes_visually_equal(a1, a2);
951                let single_text_changed = c1.len() == 1
952                    && c2.len() == 1
953                    && matches!(
954                        (&c1[0], &c2[0]),
955                        (NodeBlueprint::Text(x), NodeBlueprint::Text(y)) if x != y
956                    );
957
958                let (self_rewritten, child_inherited_changed) =
959                    if self_props_changed || parent_inherited_changed || single_text_changed {
960                        let shallow_bp = NodeBlueprint::Element {
961                            tag: *t2,
962                            classes: cls2.clone(),
963                            attributes: a2.clone(),
964                            children: Vec::new(),
965                        };
966                        let mut path_buf = Vec::new();
967                        let mut ancestors = Vec::new();
968                        let mut updated = Self::build_layout_tree_full(
969                            &shallow_bp,
970                            parent_style,
971                            &mut path_buf,
972                            ctx,
973                            stylesheets,
974                            &mut ancestors,
975                            &[],
976                            true,
977                            (false, false, false),
978                        );
979                        Self::apply_single_text_inline_intrinsic_sizing(&mut updated.style, c2);
980                        if let Some(eid) = new_bp.entity_id() {
981                            updated.entity_id = eid;
982                        }
983                        let inh_changed =
984                            !Self::inherited_style_equal(&layout_node.style, &updated.style);
985                        updated.children = std::mem::take(&mut layout_node.children);
986                        *layout_node = updated;
987                        (true, inh_changed)
988                    } else {
989                        if let Some(eid) = new_bp.entity_id() {
990                            layout_node.entity_id = eid;
991                        }
992                        (false, false)
993                    };
994
995                let parent_style_for_children = layout_node.style.clone();
996                let mut children_changed = c1.len() != c2.len();
997                let common = c1.len().min(c2.len());
998                for i in 0..common {
999                    match Self::reconcile_layout_subtree(
1000                        &c1[i],
1001                        &c2[i],
1002                        &mut layout_node.children[i],
1003                        Some(&parent_style_for_children),
1004                        child_inherited_changed,
1005                        stylesheets,
1006                        ctx,
1007                    ) {
1008                        Some(false) => {}
1009                        Some(true) => children_changed = true,
1010                        None => {
1011                            let mut path_buf = Vec::new();
1012                            let mut ancestors = Vec::new();
1013                            layout_node.children[i] = Self::build_layout_tree_full(
1014                                &c2[i],
1015                                Some(&parent_style_for_children),
1016                                &mut path_buf,
1017                                ctx,
1018                                stylesheets,
1019                                &mut ancestors,
1020                                &[],
1021                                i + 1 == c2.len(),
1022                                (false, false, false),
1023                            );
1024                            children_changed = true;
1025                        }
1026                    }
1027                }
1028                if c2.len() < c1.len() {
1029                    layout_node.children.truncate(c2.len());
1030                } else if c2.len() > c1.len() {
1031                    for (offset, nc) in c2[common..].iter().enumerate() {
1032                        let idx = common + offset;
1033                        let mut path_buf = Vec::new();
1034                        let mut ancestors = Vec::new();
1035                        layout_node.children.push(Self::build_layout_tree_full(
1036                            nc,
1037                            Some(&parent_style_for_children),
1038                            &mut path_buf,
1039                            ctx,
1040                            stylesheets,
1041                            &mut ancestors,
1042                            &[],
1043                            idx + 1 == c2.len(),
1044                            (false, false, false),
1045                        ));
1046                    }
1047                }
1048
1049                if self_rewritten || children_changed {
1050                    layout_node.inline_items.clear();
1051                    layout_node.line_boxes.clear();
1052                    layout_node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
1053                    Some(true)
1054                } else {
1055                    Some(false)
1056                }
1057            }
1058            _ => None,
1059        }
1060    }
1061
1062    /// Re-evaluates a root [`View`] closure inside an implicit root component scope (when no outer
1063    /// `#[component]` scope is active) and updates the runtime tree cleanly, preserving top-level
1064    /// unkeyed sibling isolation and triggering unmount cleanups.
1065    pub fn update_root<F: FnOnce() -> View>(&mut self, root: F) {
1066        let new_view = strata_dom::with_root_component_scope(root);
1067        self.update_view(new_view);
1068    }
1069
1070    /// Updates the application root view, incrementally reconciling unchanged subtrees
1071    /// and compiling a new display list.
1072    pub fn update_view(&mut self, new_view: View) {
1073        self.unapply_scroll_offsets();
1074        self.applied_scroll_offsets.clear();
1075        self.applied_portal_offsets.clear();
1076        let mut next_blueprint = new_view.root.flatten_fragments();
1077        next_blueprint.ensure_entity_ids();
1078        let old_blueprint = std::mem::replace(&mut self.root_blueprint, next_blueprint);
1079        self.has_resize_listeners = Self::blueprint_has_resize_listeners(&self.root_blueprint);
1080        self.ir_graph = Self::build_ir_graph(&self.root_blueprint);
1081        let sheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
1082        let sheets_unchanged = self.cached_stylesheets == sheets;
1083        if !sheets_unchanged {
1084            for sheet in &sheets {
1085                self.register_keyframes_stylesheet(sheet);
1086            }
1087            self.cached_stylesheets = sheets;
1088        }
1089        let build_start = std::time::Instant::now();
1090        let hover_safe = self.hover_is_paint_only()
1091            || self.current_hover_path.as_deref().is_none_or(|p| {
1092                !Self::node_path_has_hover_effects_with_sheets(
1093                    &old_blueprint,
1094                    p,
1095                    &self.cached_stylesheets,
1096                ) && !Self::node_path_has_hover_effects_with_sheets(
1097                    &self.root_blueprint,
1098                    p,
1099                    &self.cached_stylesheets,
1100                )
1101            });
1102        let reconciled = if self.cached_stylesheets.is_empty()
1103            && sheets_unchanged
1104            && hover_safe
1105            && self.current_focus_path.is_none()
1106        {
1107            let ctx = crate::runtime::InteractionContext {
1108                hovered_path: None,
1109                focused_path: None,
1110                is_mouse_down: self.is_mouse_down,
1111                is_dark_mode: self.is_dark_mode,
1112            };
1113            Self::reconcile_layout_subtree(
1114                &old_blueprint,
1115                &self.root_blueprint,
1116                &mut self.layout_root,
1117                None,
1118                false,
1119                &self.cached_stylesheets,
1120                &ctx,
1121            )
1122            .is_some()
1123        } else {
1124            false
1125        };
1126        if !reconciled {
1127            let ctx = self.interaction_context();
1128            self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
1129        }
1130        self.last_update_reconciled = reconciled;
1131        if perf_logging_enabled() {
1132            perf_log_ms(
1133                "build_layout_tree_update",
1134                build_start,
1135                format!(
1136                    "{} blueprint nodes -> {} layout nodes (reconciled={})",
1137                    perf_count_blueprint_nodes(&self.root_blueprint),
1138                    perf_count_layout_nodes(&self.layout_root),
1139                    reconciled
1140                ),
1141            );
1142        }
1143        self.sync_active_input_layout();
1144        self.dynamic_text_bindings.clear();
1145        let mut path_buf = Vec::new();
1146        Self::collect_dynamic_text_bindings(
1147            &self.root_blueprint,
1148            &mut path_buf,
1149            &mut self.dynamic_text_bindings,
1150        );
1151        let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
1152        let sync_start = std::time::Instant::now();
1153        self.sync_tree_animations(now_ms);
1154        if perf_logging_enabled() {
1155            perf_log_ms("sync_tree_animations", sync_start, "update_view");
1156        }
1157        self.refresh_hover_tooltip_after_view_update();
1158        self.tick_frame();
1159    }
1160
1161    /// Evaluates registered fine-grained dynamic text closures and updates target layout nodes
1162    /// directly in-place without rebuilding the blueprint tree or calling root view functions.
1163    /// Returns true if any text value changed and triggered a frame update.
1164    pub fn sync_dynamic_text(&mut self) -> bool {
1165        if self.dynamic_text_bindings.is_empty() {
1166            return false;
1167        }
1168
1169        let mut changed = false;
1170        for binding in &mut self.dynamic_text_bindings {
1171            let new_text = (binding.closure)();
1172            if new_text != binding.last_value {
1173                binding.last_value = new_text.clone();
1174                if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &binding.path)
1175                {
1176                    let is_mono = strata_layout::is_monospace_family(node.style.font_family);
1177                    let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
1178                        &new_text,
1179                        node.style.font_size,
1180                        node.style.line_height,
1181                        None,
1182                        is_mono,
1183                        node.style.font_family,
1184                        node.style.font_weight,
1185                        node.style.font_style,
1186                    );
1187                    node.style.width = strata_style::types::Dimension::Px(w);
1188                    node.style.height = strata_style::types::Dimension::Px(h);
1189                    node.geometry.content_box.width = w;
1190                    node.geometry.content_box.height = h;
1191                    node.text = Some(new_text);
1192                    node.layout_cache.is_valid = false;
1193                    changed = true;
1194                }
1195            }
1196        }
1197
1198        if changed {
1199            self.tick_frame();
1200            true
1201        } else {
1202            false
1203        }
1204    }
1205
1206    /// System cursor theme, loaded on first use. Reading cursor files from disk costs
1207    /// several milliseconds and only the MCP cursor overlay needs it.
1208    pub fn cursor_theme(&self) -> &strata_platform::CursorTheme {
1209        self.cursor_theme
1210            .get_or_init(strata_platform::CursorTheme::load_active)
1211    }
1212
1213    /// Marks only 3D viewports dirty without invalidating 2D layout or recompiling the display list.
1214    pub fn mark_viewport_3d_dirty(&mut self) {
1215        self.viewport_3d_dirty = true;
1216    }
1217
1218    /// Returns `true` when any retained 3D viewport has newer camera/geometry/overlay generations
1219    /// than what was last presented, or when `viewport_3d_dirty` was set explicitly.
1220    pub fn poll_retained_3d_dirty(&self) -> bool {
1221        if self.viewport_3d_dirty {
1222            return true;
1223        }
1224        self.tracked_retained_3d
1225            .iter()
1226            .any(|(handle, last_gens)| handle.generations() != *last_gens)
1227    }
1228
1229    /// Records the current generations of all tracked [`RetainedScene3D`] handles as presented.
1230    pub fn acknowledge_retained_3d_presented(&mut self) {
1231        self.viewport_3d_dirty = false;
1232        for (handle, last_gens) in &mut self.tracked_retained_3d {
1233            *last_gens = handle.generations();
1234        }
1235    }
1236
1237    /// Returns `true` if any `<Canvas3D>` in the current blueprint opted into uncapped presentation.
1238    pub fn has_uncapped_canvas3d(&self) -> bool {
1239        fn walk(node: &NodeBlueprint) -> bool {
1240            if let NodeBlueprint::Element {
1241                attributes,
1242                children,
1243                ..
1244            } = node
1245            {
1246                if attributes.iter().any(|a| {
1247                    matches!(
1248                        a,
1249                        strata_dom::Attribute::Property { key, value }
1250                            if key == "data-strata-uncapped" && value == "true"
1251                    )
1252                }) {
1253                    return true;
1254                }
1255                if children.iter().any(walk) {
1256                    return true;
1257                }
1258            }
1259            false
1260        }
1261        walk(&self.root_blueprint)
1262    }
1263
1264    /// Marks the compiled display list stale so the next dirty-gated compile rebuilds it.
1265    pub fn mark_paint_dirty(&mut self) {
1266        self.paint_dirty = true;
1267    }
1268
1269    /// Whether the display list is stale relative to runtime state.
1270    pub fn is_paint_dirty(&self) -> bool {
1271        self.paint_dirty
1272    }
1273
1274    /// Number of dirty-gated compiles that were skipped as unchanged.
1275    pub fn compiles_skipped(&self) -> u64 {
1276        self.compiles_skipped
1277    }
1278
1279    /// Compiles the display list only when something changed since the last compile.
1280    /// Returns true when a compile ran.
1281    pub fn compile_display_list_if_dirty(&mut self) -> bool {
1282        if !self.paint_dirty {
1283            self.compiles_skipped += 1;
1284            return false;
1285        }
1286        self.compile_display_list();
1287        true
1288    }
1289
1290    /// Generates draw commands for all computed layout rectangles using the 7-layer CSS compositor with spatial viewport scissoring.
1291    pub fn compile_display_list(&mut self) {
1292        let compile_start = std::time::Instant::now();
1293        let viewport = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
1294            Some(strata_layout::Rect::new(
1295                0.0,
1296                0.0,
1297                self.viewport_width,
1298                self.viewport_height,
1299            ))
1300        } else {
1301            None
1302        };
1303        self.display_list = strata_render::compositor::Compositor::build_display_list_with_viewport(
1304            &self.layout_root,
1305            viewport,
1306        );
1307        self.tracked_retained_3d.clear();
1308        for cmd in &self.display_list.commands {
1309            if let strata_render::compositor::DrawCommand::DrawViewport3D { scene, .. } = cmd {
1310                if let Some(handle) = scene.retained_handle() {
1311                    self.tracked_retained_3d
1312                        .push((handle.clone(), handle.generations()));
1313                }
1314            }
1315        }
1316        self.render_scrollbars();
1317        self.render_active_input_caret();
1318        self.render_hover_tooltip();
1319        self.gpu_path_pipeline
1320            .resize(self.viewport_width, self.viewport_height);
1321        self.gpu_path_pipeline
1322            .compile_frame(&self.display_list, None);
1323        self.frame_profile.compile += compile_start.elapsed();
1324        self.paint_dirty = false;
1325
1326        static COMPILE_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1327        let frame = COMPILE_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1328        if frame < 6 || frame.is_multiple_of(120) {
1329            perf_log_ms(
1330                "compile_display_list",
1331                compile_start,
1332                format!(
1333                    "frame {} {}x{} {} commands",
1334                    frame,
1335                    self.viewport_width,
1336                    self.viewport_height,
1337                    self.display_list.commands.len()
1338                ),
1339            );
1340        }
1341    }
1342
1343    /// Returns the compiled GPU path segments from the latest frame.
1344    #[inline]
1345    pub fn gpu_path_segments(&self) -> &[strata_render::gpu_path::GpuPathSegment] {
1346        &self.gpu_path_pipeline.batch.segments
1347    }
1348
1349    /// Returns the raw uniform bytes for the GPU path compute pipeline.
1350    #[inline]
1351    pub fn gpu_path_uniform_bytes(&self) -> &[u8] {
1352        self.gpu_path_pipeline.uniform_bytes()
1353    }
1354
1355    /// Processes an incoming platform event, updating viewport/scale or dispatching synthetic events.
1356    /// Returns true if a dirty layout or presentation redraw was triggered.
1357    pub fn step_event(&mut self, event: &PlatformEvent) -> bool {
1358        #[cfg(feature = "devtools")]
1359        if let Some(ref mut dt) = self.devtools {
1360            if strata_devtools::DevToolsEventInterceptor::intercept(&mut dt.hud, event) {
1361                return true;
1362            }
1363        }
1364
1365        let mut needs_redraw = match event {
1366            PlatformEvent::WindowResized { width, height } => {
1367                self.viewport_width = *width as f32;
1368                self.viewport_height = *height as f32;
1369                #[cfg(feature = "devtools")]
1370                if let Some(ref mut dt) = self.devtools {
1371                    dt.hud
1372                        .update_bounds(self.viewport_width, self.viewport_height);
1373                }
1374                self.tick_frame();
1375                true
1376            }
1377            PlatformEvent::ScaleFactorChanged { scale_factor } => {
1378                self.dpr = *scale_factor;
1379                self.tick_frame();
1380                true
1381            }
1382            PlatformEvent::WindowFocused(_) => false,
1383            PlatformEvent::WindowCloseRequested => false,
1384            PlatformEvent::Scroll {
1385                delta_x, delta_y, ..
1386            } => {
1387                let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1388                let (wheel_handled, scroll_changed) = self.dispatch_smooth_scroll_action(
1389                    self.last_mouse_pos.0,
1390                    self.last_mouse_pos.1,
1391                    *delta_x,
1392                    *delta_y,
1393                );
1394                if wheel_handled {
1395                    self.rebuild_layout_tree();
1396                    true
1397                } else {
1398                    scroll_changed || tooltip_dismissed
1399                }
1400            }
1401            PlatformEvent::AnimationTick => {
1402                let scroll_changed = self.poll_smooth_scroll();
1403                let anim_changed = self.poll_animations();
1404                let caret_changed = self.poll_caret_blink();
1405                let tooltip_changed = self.poll_hover_tooltip();
1406                scroll_changed || anim_changed || caret_changed || tooltip_changed
1407            }
1408            PlatformEvent::MouseMove { x, y } => {
1409                self.last_mouse_pos = (*x, *y);
1410                let cur = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, *x, *y);
1411                self.current_cursor = cur;
1412                let hover_changed = self.update_hover(*x, *y);
1413                self.dispatch_pointer_move_action(*x, *y).needs_redraw() || hover_changed
1414            }
1415            PlatformEvent::MouseDown { button, x, y } => {
1416                let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1417                let btn_idx = button.to_button_index();
1418                if *button == strata_platform::MouseButton::Left {
1419                    self.is_mouse_down = true;
1420                }
1421                let action = self.dispatch_pointer_down_action_with_button_and_modifiers(
1422                    *x,
1423                    *y,
1424                    btn_idx,
1425                    Default::default(),
1426                );
1427                let click_invoked = if *button != strata_platform::MouseButton::Right {
1428                    self.dispatch_mouse_click(*x, *y, btn_idx, 1)
1429                } else {
1430                    self.dispatch_context_menu(*x, *y)
1431                };
1432                let dynamic_updated = self.sync_dynamic_text();
1433                if action.needs_rebuild() || click_invoked || dynamic_updated {
1434                    self.rebuild_layout_tree();
1435                    true
1436                } else {
1437                    tooltip_dismissed || action.needs_redraw() || self.restyle_for_active_change()
1438                }
1439            }
1440            PlatformEvent::MouseUp { button, x, y } => {
1441                let btn_idx = button.to_button_index();
1442                let was_mouse_down = self.is_mouse_down;
1443                if *button == strata_platform::MouseButton::Left {
1444                    self.is_mouse_down = false;
1445                }
1446                let action = self.dispatch_pointer_up_action_with_button(*x, *y, btn_idx);
1447                if action.needs_rebuild() {
1448                    self.rebuild_layout_tree();
1449                    true
1450                } else if was_mouse_down {
1451                    action.needs_redraw() || self.restyle_for_active_change()
1452                } else {
1453                    action.needs_redraw()
1454                }
1455            }
1456            PlatformEvent::CursorLeft => {
1457                self.is_mouse_down = false;
1458                self.current_cursor = strata_platform::window::CursorIcon::Default;
1459                self.clear_hover()
1460            }
1461            PlatformEvent::KeyDown { .. }
1462            | PlatformEvent::KeyUp { .. }
1463            | PlatformEvent::ReceivedCharacter(_)
1464            | PlatformEvent::ImePreedit { .. }
1465            | PlatformEvent::ImeCommit(_) => {
1466                let tooltip_dismissed = matches!(event, PlatformEvent::KeyDown { .. })
1467                    && self.dismiss_hover_tooltip_and_repaint();
1468                let res = self.dispatch_key_event(event);
1469                let dynamic_updated = self.sync_dynamic_text();
1470                tooltip_dismissed || res.needs_redraw() || dynamic_updated
1471            }
1472            PlatformEvent::FileDrop(paths) => {
1473                let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1474                let drop_handled = self.dispatch_file_drop(paths.clone());
1475                let dynamic_updated = self.sync_dynamic_text();
1476                if drop_handled || dynamic_updated {
1477                    self.rebuild_layout_tree();
1478                    true
1479                } else {
1480                    tooltip_dismissed
1481                }
1482            }
1483            _ => false,
1484        };
1485
1486        if self.poll_dom_mutations(None) {
1487            needs_redraw = true;
1488        }
1489
1490        if needs_redraw {
1491            self.paint_dirty = true;
1492        }
1493        needs_redraw
1494    }
1495
1496    /// Number of full layout computations performed by this runtime.
1497    pub fn layout_computations(&self) -> u64 {
1498        self.layout_computations
1499    }
1500
1501    /// True when the most recent `update_view` reconciled the existing layout tree in place.
1502    pub fn last_update_reconciled(&self) -> bool {
1503        self.last_update_reconciled
1504    }
1505
1506    /// Phase timings accumulated since the last presented frame.
1507    pub fn frame_profile(&self) -> FrameProfile {
1508        self.frame_profile
1509    }
1510
1511    /// Registers an observer called with each completed [`FrameProfile`].
1512    pub fn set_frame_profile_hook(&mut self, hook: Option<Box<dyn FnMut(&FrameProfile)>>) {
1513        self.frame_profile_hook = hook.map(FrameProfileHook);
1514    }
1515
1516    /// Adds time spent rasterizing, for presenting backends that rasterize outside the runtime.
1517    pub fn record_raster_time(&mut self, elapsed: std::time::Duration) {
1518        self.frame_profile.raster += elapsed;
1519    }
1520
1521    /// Adds time spent presenting, for backends that present outside the runtime.
1522    pub fn record_present_time(&mut self, elapsed: std::time::Duration) {
1523        self.frame_profile.present += elapsed;
1524    }
1525
1526    /// Publishes the accumulated profile to the hook and starts a fresh frame.
1527    /// Returns the profile that was completed.
1528    pub fn finish_frame_profile(&mut self) -> FrameProfile {
1529        let done = std::mem::take(&mut self.frame_profile);
1530        if let Some(hook) = self.frame_profile_hook.as_mut() {
1531            (hook.0)(&done);
1532        }
1533        done
1534    }
1535
1536    /// Renders the current frame and presents it to the given surface presenter via the swapchain compositor.
1537    pub fn render_frame<P: SurfacePresenter>(
1538        &mut self,
1539        compositor: &mut SwapchainCompositor,
1540        presenter: &mut P,
1541        force_redraw: bool,
1542    ) -> Result<bool, PresentError> {
1543        #[cfg(feature = "devtools")]
1544        let frame_start = std::time::Instant::now();
1545
1546        let retained_3d_dirty = self.poll_retained_3d_dirty();
1547        if self.paint_dirty || self.frame_count == 0 || force_redraw {
1548            self.tick_frame();
1549        } else {
1550            self.compiles_skipped += 1;
1551        }
1552
1553        #[cfg(feature = "devtools")]
1554        if let Some(ref mut dt) = self.devtools {
1555            if dt.hud.state.is_visible {
1556                dt.hud
1557                    .render_overlay(Some(&dt.profiler), &mut self.display_list);
1558            }
1559        }
1560
1561        #[cfg(feature = "devtools")]
1562        let submit_start = std::time::Instant::now();
1563
1564        let present_start = std::time::Instant::now();
1565        let res = compositor.render_and_present(
1566            &self.display_list,
1567            presenter,
1568            force_redraw || retained_3d_dirty,
1569        );
1570        self.acknowledge_retained_3d_presented();
1571        self.frame_profile.present += present_start.elapsed();
1572        self.finish_frame_profile();
1573
1574        #[cfg(feature = "devtools")]
1575        if let Some(ref mut dt) = self.devtools {
1576            let submit_dur = submit_start.elapsed().as_micros() as u32;
1577            let total_dur = frame_start.elapsed().as_micros() as u32;
1578            let sample = strata_devtools::FrameTimingSample {
1579                frame_index: self.frame_count,
1580                vsync_wait_us: 0,
1581                input_dispatch_us: 100,
1582                signal_drain_us: 150,
1583                parallel_reconcile_us: 200,
1584                style_cascade_us: 250,
1585                layout_solve_us: 300,
1586                display_list_build_us: 350,
1587                gpu_submit_us: submit_dur,
1588                gpu_raster_duration_us: submit_dur.max(500),
1589                total_cpu_frame_us: total_dur,
1590                frame_budget_us: 16666,
1591                layout_shift_score: 0.0,
1592            };
1593            dt.profiler.record_sample(sample);
1594            dt.cdp_dispatcher.update_from_ir(
1595                &self.ir_graph,
1596                &self.base_node_styles,
1597                self.frame_count,
1598                self.layout_computations,
1599            );
1600        }
1601
1602        res
1603    }
1604
1605    #[cfg(feature = "devtools")]
1606    /// Initializes and mounts the in-process DevTools diagnostics suite.
1607    pub fn enable_devtools(&mut self) -> &mut strata_devtools::DevTools {
1608        if self.devtools.is_none() {
1609            let mut dt = strata_devtools::DevTools::new();
1610            dt.hud
1611                .update_bounds(self.viewport_width, self.viewport_height);
1612            self.devtools = Some(dt);
1613        }
1614        self.devtools.as_mut().unwrap()
1615    }
1616
1617    #[cfg(feature = "devtools")]
1618    /// Returns reference to DevTools diagnostics suite if active.
1619    pub fn devtools(&self) -> Option<&strata_devtools::DevTools> {
1620        self.devtools.as_ref()
1621    }
1622
1623    #[cfg(feature = "devtools")]
1624    /// Returns mutable reference to DevTools diagnostics suite if active.
1625    pub fn devtools_mut(&mut self) -> Option<&mut strata_devtools::DevTools> {
1626        self.devtools.as_mut()
1627    }
1628
1629    /// Runs the reactive event loop against a live platform window and surface presenter.
1630    pub fn run_with_window<W, E, P>(
1631        &mut self,
1632        window: &mut W,
1633        event_loop: &mut E,
1634        compositor: &mut SwapchainCompositor,
1635        presenter: &mut P,
1636    ) where
1637        W: PlatformWindow,
1638        E: EventLoop,
1639        P: SurfacePresenter,
1640    {
1641        // Initial frame presentation
1642        let _ = self.render_frame(compositor, presenter, true);
1643
1644        event_loop.run(|event, control| {
1645            match event {
1646                PlatformEvent::WindowResized { width, height } => {
1647                    compositor.resize(width, height, self.dpr);
1648                    let _ = presenter.resize(width, height);
1649                }
1650                PlatformEvent::ScaleFactorChanged { scale_factor } => {
1651                    compositor.resize(
1652                        self.viewport_width as u32,
1653                        self.viewport_height as u32,
1654                        scale_factor,
1655                    );
1656                }
1657                PlatformEvent::WindowCloseRequested => {
1658                    *control = EventLoopControl::Exit;
1659                    return;
1660                }
1661                _ => {}
1662            }
1663
1664            let needs_redraw = self.step_event(&event);
1665            window.set_cursor(self.current_cursor());
1666
1667            if needs_redraw || window.is_redraw_requested() {
1668                let _ = self.render_frame(compositor, presenter, false);
1669            }
1670
1671            // Power-saving sleep mode: if no events pending, wait for next input
1672            *control = EventLoopControl::Wait;
1673        });
1674    }
1675
1676    /// Rasterizes the current application frame to an offscreen headless FrameBuffer.
1677    pub fn render_to_framebuffer(&mut self) -> strata_render::rasterizer::FrameBuffer {
1678        self.tick_frame();
1679        let width = (self.viewport_width * self.dpr).max(1.0).ceil() as usize;
1680        let height = (self.viewport_height * self.dpr).max(1.0).ceil() as usize;
1681        let mut fb = strata_render::rasterizer::FrameBuffer::new(width, height);
1682        fb.execute_display_list(&self.display_list);
1683        fb
1684    }
1685
1686    /// Captures a headless screenshot of the current application state and writes it to a PNG file.
1687    pub fn export_png<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), String> {
1688        let fb = self.render_to_framebuffer();
1689        fb.export_png(path).map_err(|e| e.to_string())
1690    }
1691
1692    #[cfg(feature = "devtools")]
1693    /// Synchronizes the current live DOM tree, computed styles, and frame metrics to a Chrome DevTools dispatcher.
1694    pub fn sync_to_devtools(&self, dispatcher: &strata_devtools::cdp::CdpDispatcher) {
1695        dispatcher.update_from_ir(
1696            &self.ir_graph,
1697            &self.base_node_styles,
1698            self.frame_count,
1699            self.layout_computations,
1700        );
1701    }
1702}