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