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;
15#[cfg(feature = "hot-reload")]
16pub mod hmr_bridge;
17pub mod launch;
18pub mod media_host;
19pub mod platforms;
20pub mod types;
21
22mod a11y;
23mod animation;
24mod canvas3d;
25pub mod dom_hydration;
26mod events;
27mod hit_test;
28mod hover;
29mod image;
30mod input_hit_test;
31mod layout_tree;
32mod mcp;
33mod profile;
34mod scroll;
35mod scrollbar;
36mod selection;
37pub mod spatial;
38mod tailwind;
39pub mod test_support;
40
41pub use app::*;
42pub use dom_hydration::*;
43pub use edit::*;
44#[cfg(feature = "hot-reload")]
45pub use hmr_bridge::*;
46pub(crate) use image::*;
47pub use launch::*;
48pub use media_host::*;
49pub use platforms::*;
50pub use profile::{
51    take_frame_heap_alloc_delta, total_heap_alloc_stats, FrameProfile, FrameProfileHistory,
52    FrameProfileHook, FrameProfileRecord, PerfPercentileStats, PerfProfileSummary,
53    ProfilingAllocator,
54};
55pub use spatial::*;
56pub use test_support::{MatchMode, NodeQuery};
57pub use types::*;
58
59/// Live running application instance holding active state, layout tree, and display list.
60#[derive(Debug)]
61pub struct AppRuntime {
62    pub root_blueprint: NodeBlueprint,
63    pub ir_graph: strata_dom::UiIrGraph,
64    pub layout_root: LayoutNode,
65    pub display_list: DisplayList,
66    pub spatial_index: SpatialIndex,
67    pub viewport_width: f32,
68    pub viewport_height: f32,
69    pub dpr: f32,
70    pub frame_count: u64,
71    pub active_focus: Option<ActiveInput>,
72    pub input_states: std::collections::HashMap<String, strata_dom::text_input::TextInputState>,
73    pub caret_blink_epoch: std::time::Instant,
74    pub last_caret_blink_state: bool,
75    pub current_cursor: strata_platform::window::CursorIcon,
76    pub drag_selection_active: bool,
77    pub last_click_info: Option<(std::time::Instant, f32, f32, usize)>,
78    /// Press origin of a possible window drag started on a `data-app-region="drag"` surface.
79    pub pending_window_drag: Option<(f32, f32)>,
80    /// Time and position of the previous drag-region press, for double-click maximize toggling.
81    pub last_drag_click: Option<(std::time::Instant, f32, f32)>,
82    /// Hierarchical index path of the currently hovered element node.
83    pub current_hover_path: Option<Vec<usize>>,
84    /// Hierarchical index path of the currently focused element node.
85    pub current_focus_path: Option<Vec<usize>>,
86    /// Tracks the last printable character consumed by a DOM `KeyDown` listener on a non-`<input>`
87    /// focus target so an immediately following OS `ReceivedCharacter` duplicate is suppressed.
88    pub(crate) last_dom_keydown_consumed_char: Option<(char, std::time::Instant)>,
89    /// Whether pointer primary button is currently held down.
90    pub is_mouse_down: bool,
91    /// Whether dark mode is active for theme-dependent utility styling.
92    pub is_dark_mode: bool,
93    /// Last recorded pointer coordinates.
94    pub last_mouse_pos: (f32, f32),
95    /// Resolved native tooltip text (`title` or button/image `alt`) for the hovered element.
96    pub hover_tooltip_text: Option<String>,
97    /// Tree path of the element that owns `hover_tooltip_text`.
98    pub hover_tooltip_path: Option<Vec<usize>>,
99    /// Pointer coordinates used to anchor the native hover tooltip.
100    pub hover_tooltip_anchor: (f32, f32),
101    /// Timestamp when pointer dwell began on the current tooltip target.
102    pub hover_tooltip_since: Option<std::time::Instant>,
103    /// Whether the native hover tooltip popup is currently displayed.
104    pub hover_tooltip_visible: bool,
105    /// Dwell delay before a native hover tooltip becomes visible.
106    pub hover_tooltip_delay: std::time::Duration,
107    /// Visual styling and offset configuration for native hover tooltips.
108    pub hover_tooltip_style: strata_platform::HoverTooltipStyle,
109    /// Scroll offsets keyed by hierarchical tree path (e.g. [0, 1, 0]).
110    pub scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
111    /// Scroll offsets keyed by element string ID (e.g. "browser-viewport-tab-1").
112    pub scroll_offsets_by_id: std::collections::HashMap<String, (f32, f32)>,
113    /// Active scrollbars currently visible on screen.
114    pub active_scrollbars: Vec<ActiveScrollbar>,
115    /// Active drag operation on a scrollbar thumb.
116    pub scrollbar_drag: Option<ScrollbarDrag>,
117    /// Active kinetic smooth scroll animation tracker.
118    pub active_smooth_scroll: Option<SmoothScrollTracker>,
119    /// Timestamp of the last scroll interaction (for animated scrollbar thumb fade).
120    pub last_scroll_interaction: Option<std::time::Instant>,
121    /// Scroll offsets currently applied via translation to the layout tree, keyed by hierarchical tree path.
122    pub applied_scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
123    /// Anchored top-layer `<Portal>` translations currently applied to the layout tree, keyed by path.
124    pub applied_portal_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
125    /// Cached flag indicating whether the active layout tree contains any anchored `<Portal>` nodes.
126    pub(crate) has_anchored_portals: bool,
127    /// Continuous presentation epoch for animation and transition timing.
128    pub runtime_start_epoch: std::time::Instant,
129    /// Optional deterministic virtual clock override (`None` in live production execution).
130    pub(crate) manual_clock: Option<std::time::Instant>,
131    /// Coordinator for CSS transition properties across elements.
132    pub transition_manager: strata_style::transition::TransitionManager,
133    /// Coordinator for CSS keyframe animations across elements.
134    pub animation_manager: strata_style::animation::AnimationManager,
135    /// Base un-animated computed styles for all layout tree nodes keyed by deterministic node ID.
136    pub base_node_styles: std::collections::HashMap<u64, ComputedStyle>,
137    /// Previous frame's computed styles for transition diffing.
138    pub previous_node_styles: std::collections::HashMap<u64, ComputedStyle>,
139    /// Previous frame's solved border-box `(width, height)` keyed by animation node ID
140    /// so `Auto <-> 0px` transitions can interpolate smoothly between concrete pixel sizes.
141    pub previous_node_sizes: std::collections::HashMap<u64, (f32, f32)>,
142    /// Mapping from deterministic node ID to its hierarchical tree path.
143    pub node_paths: std::collections::HashMap<u64, Vec<usize>>,
144    /// Mapping from hierarchical tree path to its identity-aware animation node ID.
145    pub path_node_ids: std::collections::HashMap<Vec<usize>, u64>,
146    /// Coordinator for CSS View Transitions Module snapshots and element morphing.
147    pub view_transition_manager: crate::view_transition::ViewTransitionManager,
148    /// Whether animations or transitions were active in the prior frame (to allow clean final state settlement).
149    pub had_active_animations: bool,
150    /// Hardware GPU path compilation pipeline for direct compute shader execution.
151    pub gpu_path_pipeline: strata_render::GpuPathPipeline,
152    /// Number of full layout computations performed by this runtime (test/profiling hook).
153    pub(crate) layout_computations: u64,
154    /// True when the most recent hover transition only needed a paint refresh.
155    pub(crate) hover_paint_only: bool,
156    /// Active MCP emulated cursor state (smooth interpolation, hotspot, fade timer).
157    pub mcp_cursor: Option<strata_platform::McpCursorState>,
158    /// System cursor theme loaded dynamically or from embedded fallback assets (Yaru on Linux).
159    pub(crate) cursor_theme: std::sync::OnceLock<strata_platform::CursorTheme>,
160    /// Accessibility tree bridge connecting Strata layout and reactive DOM with AccessKit and screen readers.
161    pub a11y_bridge: strata_a11y::A11yBridge,
162    /// Latest snapshot of the accessible hierarchy.
163    pub a11y_tree: Option<strata_a11y::A11yTree>,
164    /// Number of accessibility tree synchronizations performed.
165    pub a11y_updates_count: u64,
166    /// Fine-grained dynamic text bindings mapped directly to layout node paths.
167    pub dynamic_text_bindings: Vec<DynamicTextBinding>,
168    /// Background channel receiver for live DOM mutations from scripts or browser tabs.
169    pub dom_mutation_receiver: Option<std::sync::mpsc::Receiver<strata_js::DomMutationRecord>>,
170    #[cfg(feature = "devtools")]
171    /// Integrated DevTools diagnostics suite (HUD, Profiler, Heap Tracker, CDP).
172    pub devtools: Option<strata_devtools::DevTools>,
173    /// Client-Side Decorations (CSD) controller managing titlebar geometry and drag tracking.
174    pub csd_controller: strata_platform::CsdController,
175    /// Phase timings accumulated since the last presented frame.
176    pub(crate) frame_profile: FrameProfile,
177    /// True when anything that affects painting changed since the display list was compiled.
178    pub(crate) paint_dirty: bool,
179    /// True when only retained 3D state changed without invalidating 2D layout or display list.
180    pub(crate) viewport_3d_dirty: bool,
181    /// Retained 3D scene handles in the compiled display list paired with last presented generations.
182    pub(crate) tracked_retained_3d: Vec<(strata_render::scene3d::RetainedScene3D, (u64, u64, u64))>,
183    /// Number of display-list compilations skipped because nothing changed.
184    pub(crate) compiles_skipped: u64,
185    /// Optional observer invoked with the completed profile after each present.
186    pub(crate) frame_profile_hook: Option<FrameProfileHook>,
187    /// Cached `<style>` stylesheets collected from `root_blueprint`.
188    pub(crate) cached_stylesheets: Vec<std::sync::Arc<strata_style::StyleSheet>>,
189    /// Precomputed Bloom-filter and exact tag/class/id dependency index over `cached_stylesheets`.
190    pub(crate) stylesheet_index: StylesheetSelectorIndex,
191    /// Cached document-root inherited style (`:root` / `html` / `body` custom properties & defaults).
192    pub(crate) cached_root_inherited_style: Option<ComputedStyle>,
193    /// Whether the active rendering backend consumes compiled 2D GPU path segments.
194    /// Defaults to `strata_platform::gtk_gpu_2d_enabled()` so Cairo software 2D frames
195    /// skip redundant path tessellation.
196    pub(crate) gpu_2d_paths_enabled: bool,
197    /// Active pointer capture or drag target `(tree_path, explicit_capture)`.
198    pub pointer_capture_target: Option<(Vec<usize>, bool)>,
199    /// True when the current `root_blueprint` contains any `EventType::Resize` listeners.
200    pub(crate) has_resize_listeners: bool,
201    /// Last observed `(width, height)` for elements with `onresize` listeners, keyed by node ID.
202    pub observed_element_sizes: std::collections::HashMap<u64, (f32, f32)>,
203    /// Last pointer position `(x, y)` for computing `movement_x` / `movement_y`.
204    pub(crate) last_pointer_pos: Option<(f32, f32)>,
205    /// Target `(x, y)` of an in-flight cursor warp so synthetic warp deltas are filtered.
206    pub(crate) pending_cursor_warp: Option<(f32, f32)>,
207    /// True when the most recent `update_view` call reconciled the existing layout tree in place.
208    pub(crate) last_update_reconciled: bool,
209    /// Per-update reconciliation subtree reuse and node rebuild counters.
210    pub(crate) last_reconcile_stats: ReconcileStats,
211    /// Reason the most recent `update_view` fell back to a full layout tree rebuild, if any.
212    pub(crate) last_reconcile_bailout: Option<String>,
213    /// True when the most recent paint-only hover update succeeded via `restyle_hover_subtrees_fast`.
214    pub(crate) last_hover_fast_path_used: bool,
215    /// Reason the most recent paint-only hover update bailed out of `restyle_hover_subtrees_fast`, if any.
216    pub(crate) last_hover_fast_path_bailout: Option<String>,
217    /// Cumulative count of full layout tree rebuilds across the runtime's lifetime.
218    pub(crate) full_rebuilds_count: u64,
219    /// Cumulative count of incremental reconciled view updates across the runtime's lifetime.
220    pub(crate) reconciled_updates_count: u64,
221    /// Structured attribution for why the most recent frame ran work.
222    pub(crate) last_rebuild_reason: RebuildReason,
223    /// Monotonic epoch recorded when this `AppRuntime` was instantiated (anchors Perfetto timestamps).
224    pub(crate) runtime_epoch: std::time::Instant,
225    /// Rolling ring buffer of real per-frame telemetry records for host HUDs & MCP profiling gates.
226    pub(crate) profile_history: FrameProfileHistory,
227    /// Previous frame's top-level layout rectangles used to compute real Cumulative Layout Shift (CLS).
228    pub(crate) prev_layout_cls_rects: Vec<(f32, f32, f32, f32)>,
229    /// Active native DOM drag-and-drop operation (`ondragstart`, `ondragover`, `ondrop`, etc.).
230    pub(crate) active_dom_drag: Option<ActiveDomDrag>,
231}
232
233/// Whether opt-in `[perf]` timing output is enabled through `STRATA_PERF_LOG`.
234pub(crate) fn perf_logging_enabled() -> bool {
235    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
236    *ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
237}
238
239/// Emits a gated duration measurement for the `[perf]` diagnostic channel.
240pub(crate) fn perf_log_ms(label: &str, start: std::time::Instant, detail: impl std::fmt::Display) {
241    if perf_logging_enabled() {
242        eprintln!(
243            "[perf] {}: {:.3} ms ({})",
244            label,
245            start.elapsed().as_secs_f64() * 1000.0,
246            detail
247        );
248    }
249}
250
251pub(crate) fn perf_count_layout_nodes(node: &strata_layout::LayoutNode) -> usize {
252    let mut count = 0;
253    let mut stack = vec![node];
254    while let Some(n) = stack.pop() {
255        count += 1;
256        for child in &n.children {
257            stack.push(child);
258        }
259    }
260    count
261}
262
263pub(crate) fn perf_count_blueprint_nodes(node: &NodeBlueprint) -> usize {
264    let mut count = 0;
265    let mut stack = vec![node];
266    while let Some(n) = stack.pop() {
267        count += 1;
268        match n {
269            NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
270                for child in children {
271                    stack.push(child);
272                }
273            }
274            NodeBlueprint::Text(_) | NodeBlueprint::DynamicText(_) | NodeBlueprint::Empty => {}
275        }
276    }
277    count
278}
279
280impl AppRuntime {
281    /// Builds a root [`View`] inside an implicit root component scope (when no outer `#[component]`
282    /// scope is active) and mounts a new [`AppRuntime`].
283    ///
284    /// Prefer this over [`Self::new`] when rendering plain closures containing unkeyed top-level
285    /// sibling components (`|| rsx! { <> <Child /> <Child /> </> }`) so siblings receive distinct
286    /// hook slots and run `use_effect` unmount cleanups when toggled off.
287    pub fn from_root<F: FnOnce() -> View>(
288        root: F,
289        viewport_width: f32,
290        viewport_height: f32,
291        dpr: f32,
292    ) -> Self {
293        let root_view = strata_dom::with_root_component_scope(root);
294        Self::new(root_view, viewport_width, viewport_height, dpr)
295    }
296
297    /// Creates and mounts a new application runtime from a root view.
298    pub fn new(root_view: View, viewport_width: f32, viewport_height: f32, dpr: f32) -> Self {
299        static REGISTER_JS_FETCH: std::sync::Once = std::sync::Once::new();
300        REGISTER_JS_FETCH.call_once(|| {
301            strata_js::web::set_global_fetch_handler(std::sync::Arc::new(|req| {
302                let mut web_req = strata_web_api::fetch::RequestInit {
303                    method: req.method,
304                    ..Default::default()
305                };
306                for (k, v) in req.headers {
307                    web_req.headers.set(&k, &v);
308                }
309                if let Some(body) = req.body {
310                    web_req = web_req.body(body);
311                }
312                let resp = strata_web_api::fetch::fetch(&req.url, Some(web_req))
313                    .map_err(|e| e.to_string())?;
314                Ok(strata_js::web::FetchResponse {
315                    status: resp.status,
316                    status_text: resp.status_text.clone(),
317                    headers: resp
318                        .headers
319                        .all_entries()
320                        .into_iter()
321                        .map(|(k, v)| (k.to_string(), v.to_string()))
322                        .collect(),
323                    body: resp.bytes().to_vec(),
324                })
325            }));
326        });
327
328        #[cfg(target_os = "linux")]
329        strata_platform::init_pango_text_measurement();
330
331        let mut root_blueprint = root_view.root.flatten_fragments();
332        root_blueprint.ensure_entity_ids();
333        let mut ir_graph = Self::build_ir_graph(&root_blueprint);
334
335        let build_start = std::time::Instant::now();
336        let mut layout_root = Self::build_layout_tree(&root_blueprint);
337        if perf_logging_enabled() {
338            perf_log_ms(
339                "build_layout_tree_initial",
340                build_start,
341                format!("{} layout nodes", perf_count_layout_nodes(&layout_root)),
342            );
343        }
344
345        let compute_start = std::time::Instant::now();
346        layout_root.compute_layout(viewport_width, viewport_height);
347        Self::sync_layout_to_ir(&layout_root, &mut ir_graph);
348        let mut spatial_index = SpatialIndex::new();
349        spatial_index.rebuild(&root_blueprint, &layout_root);
350        if perf_logging_enabled() {
351            perf_log_ms(
352                "compute_layout_initial",
353                compute_start,
354                format!("{}x{}", viewport_width, viewport_height),
355            );
356        }
357
358        let mut dynamic_text_bindings = Vec::new();
359        let mut path_buf = Vec::new();
360        Self::collect_dynamic_text_bindings(
361            &root_blueprint,
362            &mut path_buf,
363            &mut dynamic_text_bindings,
364        );
365
366        edit::ensure_clipboard_bridge_registered();
367        let init_now = std::time::Instant::now();
368        let mut runtime = Self {
369            root_blueprint,
370            ir_graph,
371            layout_root,
372            display_list: DisplayList::new(),
373            spatial_index,
374            viewport_width,
375            viewport_height,
376            dpr,
377            frame_count: 0,
378            active_focus: None,
379            input_states: std::collections::HashMap::new(),
380            caret_blink_epoch: init_now,
381            last_caret_blink_state: true,
382            current_cursor: strata_platform::window::CursorIcon::Default,
383            drag_selection_active: false,
384            last_click_info: None,
385            pending_window_drag: None,
386            last_drag_click: None,
387            current_hover_path: None,
388            current_focus_path: None,
389            last_dom_keydown_consumed_char: None,
390            is_mouse_down: false,
391            is_dark_mode: false,
392            last_mouse_pos: (0.0, 0.0),
393            hover_tooltip_text: None,
394            hover_tooltip_path: None,
395            hover_tooltip_anchor: (0.0, 0.0),
396            hover_tooltip_since: None,
397            hover_tooltip_visible: false,
398            hover_tooltip_delay: std::time::Duration::from_millis(450),
399            hover_tooltip_style: strata_platform::HoverTooltipStyle::default(),
400            scroll_offsets: std::collections::HashMap::new(),
401            scroll_offsets_by_id: std::collections::HashMap::new(),
402            active_scrollbars: Vec::new(),
403            scrollbar_drag: None,
404            active_smooth_scroll: None,
405            last_scroll_interaction: None,
406            applied_scroll_offsets: std::collections::HashMap::new(),
407            applied_portal_offsets: std::collections::HashMap::new(),
408            has_anchored_portals: false,
409            runtime_start_epoch: init_now,
410            manual_clock: None,
411            transition_manager: strata_style::transition::TransitionManager::new(),
412            animation_manager: strata_style::animation::AnimationManager::new(),
413            base_node_styles: std::collections::HashMap::new(),
414            previous_node_styles: std::collections::HashMap::new(),
415            previous_node_sizes: std::collections::HashMap::new(),
416            node_paths: std::collections::HashMap::new(),
417            path_node_ids: std::collections::HashMap::new(),
418            view_transition_manager: crate::view_transition::ViewTransitionManager::new(),
419            had_active_animations: false,
420            gpu_path_pipeline: strata_render::GpuPathPipeline::new(viewport_width, viewport_height),
421            layout_computations: 1,
422            hover_paint_only: false,
423            mcp_cursor: None,
424            cursor_theme: std::sync::OnceLock::new(),
425            a11y_bridge: strata_a11y::A11yBridge::new(),
426            a11y_tree: None,
427            a11y_updates_count: 0,
428            dynamic_text_bindings,
429            dom_mutation_receiver: None,
430            #[cfg(feature = "devtools")]
431            devtools: None,
432            csd_controller: strata_platform::CsdController::default(),
433            frame_profile: FrameProfile::default(),
434            paint_dirty: true,
435            viewport_3d_dirty: false,
436            tracked_retained_3d: Vec::new(),
437            compiles_skipped: 0,
438            frame_profile_hook: None,
439            cached_stylesheets: Vec::new(),
440            stylesheet_index: StylesheetSelectorIndex::default(),
441            cached_root_inherited_style: None,
442            gpu_2d_paths_enabled: strata_platform::gtk_gpu_2d_enabled(),
443            pointer_capture_target: None,
444            has_resize_listeners: false,
445            observed_element_sizes: std::collections::HashMap::new(),
446            last_pointer_pos: None,
447            pending_cursor_warp: None,
448            last_update_reconciled: false,
449            last_reconcile_stats: ReconcileStats::default(),
450            last_reconcile_bailout: None,
451            last_hover_fast_path_used: false,
452            last_hover_fast_path_bailout: None,
453            full_rebuilds_count: 1,
454            reconciled_updates_count: 0,
455            last_rebuild_reason: RebuildReason::InitialMount,
456            runtime_epoch: init_now,
457            profile_history: FrameProfileHistory::default(),
458            prev_layout_cls_rects: Vec::new(),
459            active_dom_drag: None,
460        };
461
462        runtime.has_resize_listeners =
463            Self::blueprint_has_resize_listeners(&runtime.root_blueprint);
464        let initial_sheets = Self::collect_stylesheets_from_blueprint(&runtime.root_blueprint);
465        for sheet in &initial_sheets {
466            runtime.register_keyframes_stylesheet(sheet);
467        }
468        runtime.stylesheet_index = StylesheetSelectorIndex::from_stylesheets(&initial_sheets);
469        runtime.cached_root_inherited_style = if !initial_sheets.is_empty() {
470            let ctx = runtime.interaction_context();
471            Some(Self::resolve_document_root_inherited_style(
472                &runtime.root_blueprint,
473                &initial_sheets,
474                &ctx,
475            ))
476        } else {
477            None
478        };
479        runtime.cached_stylesheets = initial_sheets;
480        runtime.sync_tree_animations(0.0);
481        runtime.apply_viewport_clamps();
482        runtime.apply_scroll_offsets();
483        runtime.dispatch_resize_observers();
484        runtime
485            .spatial_index
486            .rebuild(&runtime.root_blueprint, &runtime.layout_root);
487        runtime.update_accessibility_tree();
488        runtime.compile_display_list();
489        runtime
490    }
491
492    /// Returns the active runtime timestamp (`manual_clock` when frozen, otherwise `Instant::now()`).
493    #[inline(always)]
494    pub fn now(&self) -> std::time::Instant {
495        self.manual_clock.unwrap_or_else(std::time::Instant::now)
496    }
497
498    /// Returns milliseconds elapsed since `runtime_start_epoch` on the active runtime clock.
499    #[inline(always)]
500    pub fn now_ms(&self) -> f64 {
501        self.now()
502            .saturating_duration_since(self.runtime_start_epoch)
503            .as_secs_f64()
504            * 1000.0
505    }
506
507    /// Returns duration elapsed since `since` according to the active runtime clock.
508    #[inline(always)]
509    pub fn elapsed_since(&self, since: std::time::Instant) -> std::time::Duration {
510        self.now().saturating_duration_since(since)
511    }
512
513    /// Freezes the runtime clock at its current instant for deterministic testing and stepping.
514    pub fn freeze_clock(&mut self) -> std::time::Instant {
515        let now = self.now();
516        self.manual_clock = Some(now);
517        now
518    }
519
520    /// Freezes the runtime clock at `runtime_start_epoch` (`now_ms() == 0.0`).
521    pub fn freeze_clock_at_epoch(&mut self) -> std::time::Instant {
522        self.manual_clock = Some(self.runtime_start_epoch);
523        self.runtime_start_epoch
524    }
525
526    /// Sets the deterministic virtual clock to an explicit monotonic `Instant`.
527    pub fn set_clock(&mut self, instant: std::time::Instant) {
528        self.manual_clock = Some(instant);
529    }
530
531    /// Advances the virtual clock by `dt`, implicitly freezing from live time if currently unfrozen.
532    pub fn advance_clock(&mut self, dt: std::time::Duration) -> std::time::Instant {
533        let next = self.now() + dt;
534        self.manual_clock = Some(next);
535        next
536    }
537
538    /// Restores live wall-clock timing (`Instant::now()`).
539    pub fn use_live_clock(&mut self) {
540        self.manual_clock = None;
541    }
542
543    /// Applies runtime-relevant preferences from a [`WindowConfig`] (such as native hover
544    /// tooltip dwell delay and styling).
545    pub fn apply_window_config(&mut self, config: &WindowConfig) -> &mut Self {
546        self.hover_tooltip_delay = config.tooltip_delay;
547        self.hover_tooltip_style = config.tooltip_style;
548        if self.hover_tooltip_visible {
549            self.paint_dirty = true;
550        }
551        self
552    }
553
554    /// Sets the pointer dwell delay before native hover tooltips (`title` / `alt`) become visible.
555    pub fn set_hover_tooltip_delay(&mut self, delay: std::time::Duration) -> &mut Self {
556        self.hover_tooltip_delay = delay;
557        self
558    }
559
560    /// Sets the pointer dwell delay in milliseconds before native hover tooltips become visible.
561    pub fn set_hover_tooltip_delay_ms(&mut self, delay_ms: u64) -> &mut Self {
562        self.hover_tooltip_delay = std::time::Duration::from_millis(delay_ms);
563        self
564    }
565
566    /// Returns the configured pointer dwell delay for native hover tooltips.
567    pub fn hover_tooltip_delay(&self) -> std::time::Duration {
568        self.hover_tooltip_delay
569    }
570
571    /// Sets visual styling and offset configuration for native hover tooltips.
572    pub fn set_hover_tooltip_style(
573        &mut self,
574        style: strata_platform::HoverTooltipStyle,
575    ) -> &mut Self {
576        self.hover_tooltip_style = style;
577        if self.hover_tooltip_visible {
578            self.paint_dirty = true;
579        }
580        self
581    }
582
583    /// Returns the active visual styling configuration for native hover tooltips.
584    pub fn hover_tooltip_style(&self) -> strata_platform::HoverTooltipStyle {
585        self.hover_tooltip_style
586    }
587
588    /// Re-evaluates layout and compiles display commands for the current frame.
589    pub fn tick_frame(&mut self) -> &DisplayList {
590        self.frame_count += 1;
591        self.unapply_scroll_offsets();
592        let compute_start = std::time::Instant::now();
593        self.layout_root
594            .compute_layout(self.viewport_width, self.viewport_height);
595        Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
596        self.layout_computations += 1;
597        self.frame_profile.layout += compute_start.elapsed();
598        if perf_logging_enabled() {
599            perf_log_ms(
600                "compute_layout_tick",
601                compute_start,
602                format!(
603                    "{} layout nodes",
604                    perf_count_layout_nodes(&self.layout_root)
605                ),
606            );
607        }
608        self.apply_viewport_clamps();
609        self.apply_scroll_offsets();
610        self.sync_active_input_layout();
611        self.dispatch_resize_observers();
612        self.spatial_index
613            .rebuild(&self.root_blueprint, &self.layout_root);
614        self.update_accessibility_tree();
615        self.compile_display_list();
616        &self.display_list
617    }
618
619    /// Returns the current interaction context.
620    pub fn interaction_context(&self) -> InteractionContext<'_> {
621        InteractionContext {
622            hovered_path: self.current_hover_path.as_deref(),
623            focused_path: self.current_focus_path.as_deref(),
624            is_mouse_down: self.is_mouse_down,
625            is_dark_mode: self.is_dark_mode,
626        }
627    }
628
629    /// Sets the active dark mode state and triggers a layout and style recomputation if changed.
630    pub fn set_dark_mode(&mut self, is_dark: bool) -> bool {
631        if self.is_dark_mode != is_dark {
632            self.is_dark_mode = is_dark;
633            self.rebuild_layout_tree();
634            true
635        } else {
636            false
637        }
638    }
639
640    /// Sets the active focused element path and triggers a layout and style recomputation if changed.
641    pub fn set_focus_path(&mut self, path: Option<Vec<usize>>) -> bool {
642        if self.current_focus_path != path {
643            self.current_focus_path = path;
644            self.last_dom_keydown_consumed_char = None;
645            self.rebuild_layout_tree();
646            true
647        } else {
648            false
649        }
650    }
651
652    /// Clears and rebuilds the spatial acceleration index.
653    pub fn rebuild_spatial_index(&mut self) {
654        self.spatial_index
655            .rebuild(&self.root_blueprint, &self.layout_root);
656    }
657
658    /// Queries the front-most EntityId at point (px, py).
659    pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<strata_primitives::EntityId> {
660        self.spatial_index.query_entity_at_point(px, py)
661    }
662
663    /// Queries the front-most event listener registered for `event_type` at point (px, py).
664    pub fn query_event_at_point(
665        &self,
666        px: f32,
667        py: f32,
668        event_type: strata_dom::EventType,
669    ) -> Option<(
670        strata_primitives::EntityId,
671        std::rc::Rc<dyn Fn(strata_dom::Event)>,
672        strata_layout::Rect,
673    )> {
674        self.spatial_index.query_event_at_point(px, py, event_type)
675    }
676
677    /// Recursively locates a layout node by its EntityId.
678    pub fn find_layout_by_entity(
679        &self,
680        entity_id: strata_primitives::EntityId,
681    ) -> Option<&LayoutNode> {
682        self.layout_root.find_by_entity_id(entity_id)
683    }
684
685    /// Recursively locates a mutable layout node by its EntityId.
686    pub fn find_layout_mut_by_entity(
687        &mut self,
688        entity_id: strata_primitives::EntityId,
689    ) -> Option<&mut LayoutNode> {
690        self.layout_root.find_by_entity_id_mut(entity_id)
691    }
692
693    /// Recursively locates a blueprint node by its EntityId.
694    pub fn find_blueprint_by_entity(
695        &self,
696        entity_id: strata_primitives::EntityId,
697    ) -> Option<&NodeBlueprint> {
698        self.root_blueprint.find_by_entity_id(entity_id)
699    }
700
701    /// Queries the laid-out border-box rectangle `(x, y, width, height)` for an element by `id`.
702    pub fn query_element_rect(&self, element_id: &str) -> Option<strata_layout::Rect> {
703        fn find_rec(node: &LayoutNode, target_id: &str) -> Option<strata_layout::Rect> {
704            if node.element_id.as_deref() == Some(target_id) {
705                return Some(node.geometry.border_box);
706            }
707            for child in &node.children {
708                if let Some(rect) = find_rec(child, target_id) {
709                    return Some(rect);
710                }
711            }
712            None
713        }
714        find_rec(&self.layout_root, element_id)
715    }
716
717    /// Warps the OS pointer to window-local `(x, y)` and records the target so the
718    /// resulting synthetic motion delta is filtered from `movement_x` / `movement_y`.
719    pub fn warp_cursor(&mut self, x: f32, y: f32) {
720        self.last_pointer_pos = Some((x, y));
721        self.pending_cursor_warp = Some((x, y));
722        #[cfg(target_os = "linux")]
723        strata_platform::gtk_warp_cursor(x as f64, y as f64);
724    }
725
726    /// Alias for [`AppRuntime::warp_cursor`].
727    pub fn set_cursor_position(&mut self, x: f32, y: f32) {
728        self.warp_cursor(x, y);
729    }
730
731    /// Updates `flex_grow`, `flex_shrink`, and optional `flex_basis` on the layout node
732    /// matching `element_id` in-place, invalidating only its ancestor chain's layout cache.
733    pub fn update_element_flex(
734        &mut self,
735        element_id: &str,
736        flex_grow: f32,
737        flex_shrink: f32,
738        flex_basis: Option<strata_style::types::Dimension>,
739    ) -> bool {
740        fn update_rec(
741            node: &mut LayoutNode,
742            target_id: &str,
743            flex_grow: f32,
744            flex_shrink: f32,
745            flex_basis: Option<strata_style::types::Dimension>,
746        ) -> bool {
747            if node.element_id.as_deref() == Some(target_id) {
748                node.style.flex_grow = flex_grow;
749                node.style.flex_shrink = flex_shrink;
750                if let Some(basis) = flex_basis {
751                    node.style.flex_basis = basis;
752                }
753                node.invalidate_self_caches();
754                return true;
755            }
756            let mut changed = false;
757            for child in &mut node.children {
758                if update_rec(child, target_id, flex_grow, flex_shrink, flex_basis) {
759                    changed = true;
760                }
761            }
762            if changed {
763                node.invalidate_self_caches();
764            }
765            changed
766        }
767        update_rec(
768            &mut self.layout_root,
769            element_id,
770            flex_grow,
771            flex_shrink,
772            flex_basis,
773        )
774    }
775
776    /// Updates `flex_grow` ratios for multiple `element_id`s in-place and runs an isolated
777    /// layout-only pass without rebuilding the DOM, stylesheets, or IR graph.
778    pub fn update_split_ratios(&mut self, updates: &[(&str, f32)]) -> bool {
779        let mut any_changed = false;
780        for &(id, ratio) in updates {
781            if self.update_element_flex(id, ratio, 1.0, None) {
782                any_changed = true;
783            }
784        }
785        if any_changed {
786            self.relayout_in_place();
787        }
788        any_changed
789    }
790
791    /// Recomputes layout, scroll/viewport clamps, resize observers, spatial index, and
792    /// display list in-place without rebuilding `layout_root` or `ir_graph`.
793    pub fn relayout_in_place(&mut self) {
794        self.unapply_scroll_offsets();
795        let compute_start = std::time::Instant::now();
796        self.layout_root
797            .compute_layout(self.viewport_width, self.viewport_height);
798        self.layout_computations += 1;
799        self.frame_profile.layout += compute_start.elapsed();
800        self.apply_viewport_clamps();
801        self.apply_scroll_offsets();
802        self.dispatch_resize_observers();
803        self.spatial_index
804            .rebuild(&self.root_blueprint, &self.layout_root);
805        self.paint_dirty = true;
806        self.compile_display_list();
807    }
808
809    /// Returns true if any element in `bp` registers an `EventType::Resize` listener.
810    pub(crate) fn blueprint_has_resize_listeners(bp: &NodeBlueprint) -> bool {
811        match bp {
812            NodeBlueprint::Element {
813                attributes,
814                children,
815                ..
816            } => {
817                attributes.iter().any(|a| {
818                    matches!(
819                        a,
820                        strata_dom::Attribute::EventListener {
821                            event: strata_dom::EventType::Resize,
822                            ..
823                        }
824                    )
825                }) || children.iter().any(Self::blueprint_has_resize_listeners)
826            }
827            NodeBlueprint::Fragment(children) => {
828                children.iter().any(Self::blueprint_has_resize_listeners)
829            }
830            _ => false,
831        }
832    }
833
834    /// Dispatches `EventType::Resize` (`onresize`) callbacks for any element whose laid-out
835    /// `(width, height)` changed since the last observation. Returns `true` if any callback fired.
836    pub fn dispatch_resize_observers(&mut self) -> bool {
837        if !self.has_resize_listeners {
838            return false;
839        }
840        let mut pending: Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)> =
841            Vec::new();
842        let mut active_ids = std::collections::HashSet::new();
843        let mut path = Vec::new();
844
845        #[allow(clippy::too_many_arguments)]
846        fn collect_rec(
847            bp: &NodeBlueprint,
848            layout: &LayoutNode,
849            path: &mut Vec<usize>,
850            path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
851            observed: &mut std::collections::HashMap<u64, (f32, f32)>,
852            active_ids: &mut std::collections::HashSet<u64>,
853            pending: &mut Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)>,
854        ) {
855            if let NodeBlueprint::Element {
856                attributes,
857                children,
858                ..
859            } = bp
860            {
861                let node_id = path_node_ids
862                    .get(path)
863                    .copied()
864                    .unwrap_or_else(|| path_to_node_id(path));
865                let mut resize_handlers = Vec::new();
866                for attr in attributes {
867                    if let strata_dom::Attribute::EventListener {
868                        event: strata_dom::EventType::Resize,
869                        handler,
870                    } = attr
871                    {
872                        resize_handlers.push(handler.clone());
873                    }
874                }
875                if !resize_handlers.is_empty() {
876                    active_ids.insert(node_id);
877                    let w = layout.geometry.border_box.width;
878                    let h = layout.geometry.border_box.height;
879                    let changed = match observed.get(&node_id) {
880                        Some(&(pw, ph)) => (w - pw).abs() > 0.25 || (h - ph).abs() > 0.25,
881                        None => true,
882                    };
883                    if changed {
884                        observed.insert(node_id, (w, h));
885                        for handler in resize_handlers {
886                            pending.push((handler, layout.geometry.border_box));
887                        }
888                    }
889                }
890                for (idx, child_layout) in layout.children.iter().enumerate() {
891                    if let Some(child_bp) = children.get(idx) {
892                        path.push(idx);
893                        collect_rec(
894                            child_bp,
895                            child_layout,
896                            path,
897                            path_node_ids,
898                            observed,
899                            active_ids,
900                            pending,
901                        );
902                        path.pop();
903                    }
904                }
905            }
906        }
907
908        collect_rec(
909            &self.root_blueprint,
910            &self.layout_root,
911            &mut path,
912            &self.path_node_ids,
913            &mut self.observed_element_sizes,
914            &mut active_ids,
915            &mut pending,
916        );
917        self.observed_element_sizes
918            .retain(|id, _| active_ids.contains(id));
919
920        if pending.is_empty() {
921            return false;
922        }
923        for (handler, rect) in pending {
924            let mut ev = strata_dom::Event::new(strata_dom::EventType::Resize);
925            ev.client_x = rect.x as f64;
926            ev.client_y = rect.y as f64;
927            ev.offset_x = rect.width as f64;
928            ev.offset_y = rect.height as f64;
929            ev.width = rect.width as f64;
930            ev.height = rect.height as f64;
931            handler(ev);
932        }
933        true
934    }
935
936    fn element_attr_value<'a>(
937        attrs: &'a [strata_dom::Attribute],
938        key_name: &str,
939    ) -> Option<&'a str> {
940        attrs.iter().find_map(|a| match a {
941            strata_dom::Attribute::Property { key, value } if key == key_name => {
942                Some(value.as_str())
943            }
944            _ => None,
945        })
946    }
947
948    fn attributes_visually_equal(a: &[strata_dom::Attribute], b: &[strata_dom::Attribute]) -> bool {
949        let mut iter_a = a.iter().filter(|attr| {
950            !matches!(
951                attr,
952                strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
953            )
954        });
955        let mut iter_b = b.iter().filter(|attr| {
956            !matches!(
957                attr,
958                strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
959            )
960        });
961        loop {
962            match (iter_a.next(), iter_b.next()) {
963                (None, None) => return true,
964                (Some(x), Some(y)) => match (x, y) {
965                    (
966                        strata_dom::Attribute::Property { key: k1, value: v1 },
967                        strata_dom::Attribute::Property { key: k2, value: v2 },
968                    ) if k1 == k2 && v1 == v2 => {}
969                    (
970                        strata_dom::Attribute::DirectStyle(d1),
971                        strata_dom::Attribute::DirectStyle(d2),
972                    ) if std::rc::Rc::ptr_eq(d1, d2) => {}
973                    (
974                        strata_dom::Attribute::ScenePayload(s1),
975                        strata_dom::Attribute::ScenePayload(s2),
976                    ) if std::sync::Arc::ptr_eq(s1, s2) => {}
977                    _ => return false,
978                },
979                _ => return false,
980            }
981        }
982    }
983
984    fn inherited_style_equal(
985        a: &strata_style::ComputedStyle,
986        b: &strata_style::ComputedStyle,
987    ) -> bool {
988        a.color == b.color
989            && a.font_family == b.font_family
990            && a.font_size == b.font_size
991            && a.root_font_size == b.root_font_size
992            && a.font_weight == b.font_weight
993            && a.font_style == b.font_style
994            && a.text_align == b.text_align
995            && a.line_height == b.line_height
996            && a.letter_spacing == b.letter_spacing
997            && a.text_decoration == b.text_decoration
998            && a.text_transform == b.text_transform
999            && a.text_overflow == b.text_overflow
1000            && a.white_space == b.white_space
1001            && a.cursor == b.cursor
1002            && a.user_select == b.user_select
1003            && a.pointer_events == b.pointer_events
1004            && a.visibility == b.visibility
1005            && a.caret_color == b.caret_color
1006            && a.border_collapse == b.border_collapse
1007            && a.border_spacing == b.border_spacing
1008            && a.caption_side == b.caption_side
1009            && a.custom_properties == b.custom_properties
1010    }
1011
1012    fn blueprint_visually_equal(a: &NodeBlueprint, b: &NodeBlueprint) -> bool {
1013        match (a, b) {
1014            (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => t1 == t2,
1015            (NodeBlueprint::Empty, NodeBlueprint::Empty) => true,
1016            (
1017                NodeBlueprint::Element {
1018                    tag: t1,
1019                    classes: cls1,
1020                    attributes: a1,
1021                    children: c1,
1022                },
1023                NodeBlueprint::Element {
1024                    tag: t2,
1025                    classes: cls2,
1026                    attributes: a2,
1027                    children: c2,
1028                },
1029            ) => {
1030                t1 == t2
1031                    && cls1 == cls2
1032                    && c1.len() == c2.len()
1033                    && Self::attributes_visually_equal(a1, a2)
1034                    && c1
1035                        .iter()
1036                        .zip(c2.iter())
1037                        .all(|(x, y)| Self::blueprint_visually_equal(x, y))
1038            }
1039            _ => false,
1040        }
1041    }
1042
1043    /// Reconciles `layout_node` in-place from `old_bp` to `new_bp`, preserving W3C CSS property
1044    /// inheritance top-down from `parent_style`.
1045    /// Returns `None` if a structural mismatch requires a full subtree rebuild,
1046    /// `Some(true)` if any layout cache in this subtree was invalidated, or
1047    /// Materializes `CascadeElementMeta` for a single blueprint element at `node_path` on demand
1048    /// (called only when a node actually needs style re-resolution during reconciliation or fast hover).
1049    pub(crate) fn materialize_cascade_meta(
1050        bp: &NodeBlueprint,
1051        node_path: &[usize],
1052        ctx: &crate::runtime::InteractionContext,
1053        group_state: (bool, bool, bool),
1054    ) -> Option<CascadeElementMeta> {
1055        let NodeBlueprint::Element {
1056            tag,
1057            classes,
1058            attributes,
1059            ..
1060        } = bp
1061        else {
1062            return None;
1063        };
1064        if Self::is_style_tag(tag) {
1065            return None;
1066        }
1067        let is_hovered = ctx.hovered_path.is_some_and(|h| h.starts_with(node_path));
1068        let is_focused = ctx.focused_path.is_some_and(|f| f.starts_with(node_path));
1069        let is_active = is_hovered && ctx.is_mouse_down;
1070        let is_disabled = attributes.iter().any(|attr| match attr {
1071            strata_dom::Attribute::Property { key, value } => {
1072                key.eq_ignore_ascii_case("disabled") && !value.eq_ignore_ascii_case("false")
1073            }
1074            _ => false,
1075        });
1076        let (class_vec, id_val, attr_vec) = Self::extract_element_selector_meta(classes, attributes);
1077        Some(CascadeElementMeta {
1078            tag: Self::tag_as_str(tag),
1079            classes: class_vec,
1080            id: id_val,
1081            attributes: attr_vec,
1082            pseudo_state: strata_style::selector::PseudoState {
1083                is_hovered,
1084                is_focused,
1085                is_active,
1086                is_disabled,
1087                is_dark: ctx.is_dark_mode,
1088                is_group_hovered: group_state.0,
1089                is_group_focused: group_state.1,
1090                is_group_active: group_state.2,
1091            },
1092        })
1093    }
1094
1095    pub(crate) fn materialize_ancestor_metas(
1096        ancestor_stack: &[(&NodeBlueprint, (bool, bool, bool))],
1097        path_buf: &[usize],
1098        ctx: &crate::runtime::InteractionContext,
1099        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1100        sheet_index: &StylesheetSelectorIndex,
1101    ) -> Vec<CascadeElementMeta> {
1102        if stylesheets.is_empty() || !sheet_index.has_descendant_combinator_rules {
1103            return Vec::new();
1104        }
1105        let mut out = Vec::with_capacity(ancestor_stack.len());
1106        for (depth_idx, &(anc_bp, anc_group)) in ancestor_stack.iter().enumerate() {
1107            let anc_path = &path_buf[..depth_idx.min(path_buf.len())];
1108            if let Some(meta) = Self::materialize_cascade_meta(anc_bp, anc_path, ctx, anc_group) {
1109                out.push(meta);
1110            }
1111        }
1112        out
1113    }
1114
1115    pub(crate) fn materialize_preceding_sibling_metas(
1116        siblings: &[NodeBlueprint],
1117        child_idx: usize,
1118        parent_path: &[usize],
1119        ctx: &crate::runtime::InteractionContext,
1120        group_state: (bool, bool, bool),
1121        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1122        sheet_index: &StylesheetSelectorIndex,
1123    ) -> Vec<CascadeElementMeta> {
1124        if stylesheets.is_empty()
1125            || !sheet_index.has_sibling_combinator_or_positional_rules
1126            || child_idx == 0
1127        {
1128            return Vec::new();
1129        }
1130        let mut sib_path = Vec::with_capacity(parent_path.len() + 1);
1131        sib_path.extend_from_slice(parent_path);
1132        sib_path.push(0);
1133        let mut out = Vec::with_capacity(child_idx);
1134        for (j, sib_bp) in siblings[..child_idx].iter().enumerate() {
1135            if let Some(last) = sib_path.last_mut() {
1136                *last = j;
1137            }
1138            if let Some(meta) = Self::materialize_cascade_meta(sib_bp, &sib_path, ctx, group_state) {
1139                out.push(meta);
1140            }
1141        }
1142        out
1143    }
1144
1145    /// Incrementally reconciles `layout_node` in place against `old_bp` and `new_bp`.
1146    ///
1147    /// Supports static `<style>` sheets (`:root` variables, class/tag/combinator rules),
1148    /// active `:focus`/`:hover` interaction paths, and `group-*` markers while keeping
1149    /// unchanged subtrees O(1) zero-allocation.
1150    /// Returns `None` if this node cannot be reconciled in place (caller should rebuild it),
1151    /// `Some(true)` if any style or descendant changed (layout cache invalidated), or
1152    /// `Some(false)` if this entire subtree is visually and structurally identical.
1153    #[allow(clippy::too_many_arguments)]
1154    fn reconcile_layout_subtree<'a>(
1155        old_bp: &NodeBlueprint,
1156        new_bp: &'a NodeBlueprint,
1157        layout_node: &mut LayoutNode,
1158        parent_style: Option<&strata_style::ComputedStyle>,
1159        parent_inherited_changed: bool,
1160        ancestor_selector_changed: bool,
1161        force_restyle_self: bool,
1162        path_buf: &mut Vec<usize>,
1163        ancestor_stack: &mut Vec<(&'a NodeBlueprint, (bool, bool, bool))>,
1164        sibling_bps: &[NodeBlueprint],
1165        sibling_idx: usize,
1166        is_last_element_child: bool,
1167        group_state: (bool, bool, bool),
1168        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1169        sheet_index: &StylesheetSelectorIndex,
1170        ctx: &crate::runtime::InteractionContext,
1171        stats: &mut ReconcileStats,
1172    ) -> Option<bool> {
1173        match (old_bp, new_bp) {
1174            (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => {
1175                if t1 == t2 && !parent_inherited_changed && !force_restyle_self {
1176                    stats.reused_subtrees += 1;
1177                    Some(false)
1178                } else {
1179                    *layout_node = Self::build_text_leaf_layout_node(t2.clone(), parent_style);
1180                    stats.rebuilt_nodes += 1;
1181                    Some(true)
1182                }
1183            }
1184            (NodeBlueprint::Empty, NodeBlueprint::Empty) => {
1185                stats.reused_subtrees += 1;
1186                Some(false)
1187            }
1188            (
1189                NodeBlueprint::Element { tag: t1, .. },
1190                NodeBlueprint::Element { tag: t2, .. },
1191            ) if t1 == t2 && Self::is_style_tag(t1) => {
1192                if let Some(eid) = new_bp.entity_id() {
1193                    layout_node.entity_id = eid;
1194                }
1195                stats.reused_subtrees += 1;
1196                Some(false)
1197            }
1198            (
1199                NodeBlueprint::Element { tag: t1, .. },
1200                NodeBlueprint::Element { tag: t2, .. },
1201            ) if t1 == t2
1202                && matches!(
1203                    t1,
1204                    strata_dom::Tag::Svg
1205                        | strata_dom::Tag::Path
1206                        | strata_dom::Tag::Input
1207                        | strata_dom::Tag::Textarea
1208                        | strata_dom::Tag::Img
1209                        | strata_dom::Tag::Canvas
1210                        | strata_dom::Tag::Custom("Canvas3D")
1211                ) =>
1212            {
1213                if !parent_inherited_changed
1214                    && !ancestor_selector_changed
1215                    && !force_restyle_self
1216                    && Self::blueprint_visually_equal(old_bp, new_bp)
1217                {
1218                    if let Some(eid) = new_bp.entity_id() {
1219                        layout_node.entity_id = eid;
1220                    }
1221                    stats.reused_subtrees += 1;
1222                    Some(false)
1223                } else {
1224                    None
1225                }
1226            }
1227            (
1228                NodeBlueprint::Element {
1229                    tag: t1,
1230                    classes: cls1,
1231                    attributes: a1,
1232                    children: c1,
1233                },
1234                NodeBlueprint::Element {
1235                    tag: t2,
1236                    classes: cls2,
1237                    attributes: a2,
1238                    children: c2,
1239                },
1240            ) if t1 == t2
1241                && !layout_node.is_top_layer
1242                && layout_node.children.len() == c1.len()
1243                && Self::element_attr_value(a1, "key") == Self::element_attr_value(a2, "key")
1244                && Self::element_attr_value(a1, "id") == Self::element_attr_value(a2, "id") =>
1245            {
1246                let self_props_changed = cls1 != cls2 || !Self::attributes_visually_equal(a1, a2);
1247                let single_text_changed = c1.len() == 1
1248                    && c2.len() == 1
1249                    && matches!(
1250                        (&c1[0], &c2[0]),
1251                        (NodeBlueprint::Text(x), NodeBlueprint::Text(y)) if x != y
1252                    );
1253
1254                let (self_rewritten, child_inherited_changed) = if self_props_changed
1255                    || parent_inherited_changed
1256                    || ancestor_selector_changed
1257                    || force_restyle_self
1258                    || single_text_changed
1259                {
1260                    let shallow_bp = NodeBlueprint::Element {
1261                        tag: *t2,
1262                        classes: cls2.clone(),
1263                        attributes: a2.clone(),
1264                        children: Vec::new(),
1265                    };
1266                    let mut ancestors_meta = Self::materialize_ancestor_metas(
1267                        ancestor_stack,
1268                        path_buf,
1269                        ctx,
1270                        stylesheets,
1271                        sheet_index,
1272                    );
1273                    let parent_path_len = path_buf.len().saturating_sub(1);
1274                    let preceding_sibs = if !path_buf.is_empty() {
1275                        Self::materialize_preceding_sibling_metas(
1276                            sibling_bps,
1277                            sibling_idx,
1278                            &path_buf[..parent_path_len],
1279                            ctx,
1280                            group_state,
1281                            stylesheets,
1282                            sheet_index,
1283                        )
1284                    } else {
1285                        Vec::new()
1286                    };
1287                    let mut updated = Self::build_layout_tree_full(
1288                        &shallow_bp,
1289                        parent_style,
1290                        path_buf,
1291                        ctx,
1292                        stylesheets,
1293                        &mut ancestors_meta,
1294                        &preceding_sibs,
1295                        is_last_element_child,
1296                        group_state,
1297                    );
1298                    Self::apply_single_text_inline_intrinsic_sizing(&mut updated.style, c2);
1299                    if let Some(eid) = new_bp.entity_id() {
1300                        updated.entity_id = eid;
1301                    }
1302                    let inh_changed =
1303                        !Self::inherited_style_equal(&layout_node.style, &updated.style);
1304                    updated.children = std::mem::take(&mut layout_node.children);
1305                    *layout_node = updated;
1306                    stats.rebuilt_nodes += 1;
1307                    (true, inh_changed)
1308                } else {
1309                    if let Some(eid) = new_bp.entity_id() {
1310                        layout_node.entity_id = eid;
1311                    }
1312                    (false, false)
1313                };
1314
1315                let child_group_state = if Self::classes_have_group_marker(cls2) {
1316                    let self_hovered = ctx.hovered_path.is_some_and(|h| h.starts_with(path_buf));
1317                    let self_focused = ctx.focused_path.is_some_and(|f| f.starts_with(path_buf));
1318                    let self_active = self_hovered && ctx.is_mouse_down;
1319                    (
1320                        group_state.0 || self_hovered,
1321                        group_state.1 || self_focused,
1322                        group_state.2 || self_active,
1323                    )
1324                } else {
1325                    group_state
1326                };
1327                let old_group_marker = Self::classes_have_group_marker(cls1);
1328                let group_marker_changed = old_group_marker != Self::classes_have_group_marker(cls2);
1329                let next_ancestor_selector_changed = ancestor_selector_changed
1330                    || group_marker_changed
1331                    || (self_props_changed && sheet_index.has_descendant_combinator_rules);
1332
1333                let parent_style_for_children = layout_node.style.clone();
1334                let child_count_changed = c1.len() != c2.len();
1335                let mut children_changed = child_count_changed;
1336                let common = c1.len().min(c2.len());
1337                let last_elem_idx = if !stylesheets.is_empty()
1338                    && sheet_index.has_sibling_combinator_or_positional_rules
1339                {
1340                    c2.iter().rposition(|bp| {
1341                        matches!(bp, NodeBlueprint::Element { tag, .. } if !Self::is_style_tag(tag))
1342                    })
1343                } else {
1344                    None
1345                };
1346
1347                ancestor_stack.push((new_bp, group_state));
1348                let mut preceding_sibling_mutated = false;
1349
1350                for i in 0..common {
1351                    path_buf.push(i);
1352                    let is_last_child = last_elem_idx.map_or(i + 1 == c2.len(), |l| l == i);
1353                    // If child count changed and a hover/focus path runs through this child,
1354                    // force re-style so shifted indices never keep stale pseudo styles.
1355                    let interaction_shifted = child_count_changed
1356                        && (ctx.hovered_path.is_some_and(|h| h.starts_with(path_buf))
1357                            || ctx.focused_path.is_some_and(|f| f.starts_with(path_buf)));
1358                    let positional_affected = sheet_index.has_sibling_combinator_or_positional_rules
1359                        && (preceding_sibling_mutated
1360                            || (child_count_changed && (i + 1 == common || is_last_child)));
1361                    let child_force_restyle = interaction_shifted || positional_affected;
1362
1363                    match Self::reconcile_layout_subtree(
1364                        &c1[i],
1365                        &c2[i],
1366                        &mut layout_node.children[i],
1367                        Some(&parent_style_for_children),
1368                        child_inherited_changed,
1369                        next_ancestor_selector_changed,
1370                        child_force_restyle,
1371                        path_buf,
1372                        ancestor_stack,
1373                        c2,
1374                        i,
1375                        is_last_child,
1376                        child_group_state,
1377                        stylesheets,
1378                        sheet_index,
1379                        ctx,
1380                        stats,
1381                    ) {
1382                        Some(false) => {}
1383                        Some(true) => {
1384                            children_changed = true;
1385                            if sheet_index.has_sibling_combinator_or_positional_rules {
1386                                preceding_sibling_mutated = true;
1387                            }
1388                        }
1389                        None => {
1390                            let mut ancestors_meta = Self::materialize_ancestor_metas(
1391                                ancestor_stack,
1392                                path_buf,
1393                                ctx,
1394                                stylesheets,
1395                                sheet_index,
1396                            );
1397                            let parent_path_len = path_buf.len().saturating_sub(1);
1398                            let preceding_sibs = Self::materialize_preceding_sibling_metas(
1399                                c2,
1400                                i,
1401                                &path_buf[..parent_path_len],
1402                                ctx,
1403                                child_group_state,
1404                                stylesheets,
1405                                sheet_index,
1406                            );
1407                            layout_node.children[i] = Self::build_layout_tree_full(
1408                                &c2[i],
1409                                Some(&parent_style_for_children),
1410                                path_buf,
1411                                ctx,
1412                                stylesheets,
1413                                &mut ancestors_meta,
1414                                &preceding_sibs,
1415                                is_last_child,
1416                                child_group_state,
1417                            );
1418                            stats.rebuilt_nodes += 1;
1419                            children_changed = true;
1420                            if sheet_index.has_sibling_combinator_or_positional_rules {
1421                                preceding_sibling_mutated = true;
1422                            }
1423                        }
1424                    }
1425                    path_buf.pop();
1426                }
1427
1428                if c2.len() < c1.len() {
1429                    layout_node.children.truncate(c2.len());
1430                } else if c2.len() > c1.len() {
1431                    for (offset, nc) in c2[common..].iter().enumerate() {
1432                        let idx = common + offset;
1433                        path_buf.push(idx);
1434                        let is_last_child = last_elem_idx.map_or(idx + 1 == c2.len(), |l| l == idx);
1435                        let mut ancestors_meta = Self::materialize_ancestor_metas(
1436                            ancestor_stack,
1437                            path_buf,
1438                            ctx,
1439                            stylesheets,
1440                            sheet_index,
1441                        );
1442                        let parent_path_len = path_buf.len().saturating_sub(1);
1443                        let preceding_sibs = Self::materialize_preceding_sibling_metas(
1444                            c2,
1445                            idx,
1446                            &path_buf[..parent_path_len],
1447                            ctx,
1448                            child_group_state,
1449                            stylesheets,
1450                            sheet_index,
1451                        );
1452                        layout_node.children.push(Self::build_layout_tree_full(
1453                            nc,
1454                            Some(&parent_style_for_children),
1455                            path_buf,
1456                            ctx,
1457                            stylesheets,
1458                            &mut ancestors_meta,
1459                            &preceding_sibs,
1460                            is_last_child,
1461                            child_group_state,
1462                        ));
1463                        stats.rebuilt_nodes += 1;
1464                        path_buf.pop();
1465                    }
1466                }
1467                ancestor_stack.pop();
1468
1469                if self_rewritten || children_changed {
1470                    layout_node.inline_items.clear();
1471                    layout_node.line_boxes.clear();
1472                    layout_node.invalidate_self_caches();
1473                    Some(true)
1474                } else {
1475                    stats.reused_subtrees += 1;
1476                    Some(false)
1477                }
1478            }
1479            _ => None,
1480        }
1481    }
1482
1483    /// Re-evaluates a root [`View`] closure inside an implicit root component scope (when no outer
1484    /// `#[component]` scope is active) and updates the runtime tree cleanly, preserving top-level
1485    /// unkeyed sibling isolation and triggering unmount cleanups.
1486    pub fn update_root<F: FnOnce() -> View>(&mut self, root: F) {
1487        let view_start = std::time::Instant::now();
1488        let new_view = strata_dom::with_root_component_scope(root);
1489        self.frame_profile.view_render += view_start.elapsed();
1490        self.update_view(new_view);
1491    }
1492
1493    /// Updates the application root view, incrementally reconciling unchanged subtrees
1494    /// and compiling a new display list.
1495    pub fn update_view(&mut self, new_view: View) {
1496        self.unapply_scroll_offsets();
1497        self.applied_scroll_offsets.clear();
1498        self.applied_portal_offsets.clear();
1499        if self.had_active_animations || self.has_active_animations() {
1500            self.restore_base_styles_to_layout_tree();
1501        }
1502        let mut next_blueprint = new_view.root.flatten_fragments();
1503        next_blueprint.ensure_entity_ids();
1504        let old_blueprint = std::mem::replace(&mut self.root_blueprint, next_blueprint);
1505        self.has_resize_listeners = Self::blueprint_has_resize_listeners(&self.root_blueprint);
1506        self.ir_graph = Self::build_ir_graph(&self.root_blueprint);
1507        let sheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
1508        let sheets_unchanged = self.cached_stylesheets == sheets;
1509        if !sheets_unchanged {
1510            for sheet in &sheets {
1511                self.register_keyframes_stylesheet(sheet);
1512            }
1513            self.stylesheet_index = StylesheetSelectorIndex::from_stylesheets(&sheets);
1514            self.cached_stylesheets = sheets;
1515        }
1516        self.capture_previous_node_sizes();
1517        let build_start = std::time::Instant::now();
1518        let mut stats = ReconcileStats::default();
1519        let mut bailout_reason: Option<String> = None;
1520
1521        let hovered_owned = self.current_hover_path.clone();
1522        let focused_owned = self.current_focus_path.clone();
1523        let ctx = crate::runtime::InteractionContext {
1524            hovered_path: hovered_owned.as_deref(),
1525            focused_path: focused_owned.as_deref(),
1526            is_mouse_down: self.is_mouse_down,
1527            is_dark_mode: self.is_dark_mode,
1528        };
1529        let next_root_inherited = if !self.cached_stylesheets.is_empty() {
1530            Some(Self::resolve_document_root_inherited_style(
1531                &self.root_blueprint,
1532                &self.cached_stylesheets,
1533                &ctx,
1534            ))
1535        } else {
1536            None
1537        };
1538        let root_inherited_changed = match (&self.cached_root_inherited_style, &next_root_inherited)
1539        {
1540            (Some(a), Some(b)) => !Self::inherited_style_equal(a, b),
1541            (None, None) => false,
1542            _ => true,
1543        };
1544
1545        let reconciled = if sheets_unchanged {
1546            let mut path_buf = Vec::new();
1547            let mut ancestor_stack = Vec::new();
1548            let ok = Self::reconcile_layout_subtree(
1549                &old_blueprint,
1550                &self.root_blueprint,
1551                &mut self.layout_root,
1552                next_root_inherited.as_ref(),
1553                root_inherited_changed,
1554                false,
1555                false,
1556                &mut path_buf,
1557                &mut ancestor_stack,
1558                &[],
1559                0,
1560                true,
1561                (false, false, false),
1562                &self.cached_stylesheets,
1563                &self.stylesheet_index,
1564                &ctx,
1565                &mut stats,
1566            )
1567            .is_some();
1568            if !ok {
1569                bailout_reason = Some("RootStructuralMismatch".to_string());
1570            }
1571            ok
1572        } else {
1573            bailout_reason = Some("StylesheetsChanged".to_string());
1574            false
1575        };
1576        self.cached_root_inherited_style = next_root_inherited;
1577
1578        if !reconciled {
1579            let ctx = self.interaction_context();
1580            self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
1581            self.full_rebuilds_count += 1;
1582            if let Some(ref reason) = bailout_reason {
1583                self.last_rebuild_reason = RebuildReason::LayoutReconcileBailout(reason.clone());
1584            }
1585        } else {
1586            self.reconciled_updates_count += 1;
1587        }
1588        self.last_update_reconciled = reconciled;
1589        self.last_reconcile_stats = stats;
1590        self.last_reconcile_bailout = bailout_reason;
1591        self.frame_profile.reconcile += build_start.elapsed();
1592        if perf_logging_enabled() {
1593            perf_log_ms(
1594                "build_layout_tree_update",
1595                build_start,
1596                format!(
1597                    "{} blueprint nodes -> {} layout nodes (reconciled={}, reused={}, rebuilt={})",
1598                    perf_count_blueprint_nodes(&self.root_blueprint),
1599                    perf_count_layout_nodes(&self.layout_root),
1600                    reconciled,
1601                    stats.reused_subtrees,
1602                    stats.rebuilt_nodes
1603                ),
1604            );
1605        }
1606        self.sync_active_input_layout();
1607        self.dynamic_text_bindings.clear();
1608        let mut path_buf = Vec::new();
1609        Self::collect_dynamic_text_bindings(
1610            &self.root_blueprint,
1611            &mut path_buf,
1612            &mut self.dynamic_text_bindings,
1613        );
1614        let now_ms = self.now_ms();
1615        let sync_start = std::time::Instant::now();
1616        self.sync_tree_animations(now_ms);
1617        if self.had_active_animations || self.has_active_animations() {
1618            strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
1619        }
1620        if perf_logging_enabled() {
1621            perf_log_ms("sync_tree_animations", sync_start, "update_view");
1622        }
1623        self.refresh_hover_tooltip_after_view_update();
1624        self.tick_frame();
1625    }
1626
1627    /// Evaluates registered fine-grained dynamic text closures and updates target layout nodes
1628    /// directly in-place without rebuilding the blueprint tree or calling root view functions.
1629    /// Returns true if any text value changed and triggered a frame update.
1630    pub fn sync_dynamic_text(&mut self) -> bool {
1631        if self.dynamic_text_bindings.is_empty() {
1632            return false;
1633        }
1634
1635        let mut changed = false;
1636        for binding in &mut self.dynamic_text_bindings {
1637            let new_text = (binding.closure)();
1638            if new_text != binding.last_value {
1639                binding.last_value = new_text.clone();
1640                let mut node_updated = false;
1641                if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &binding.path)
1642                {
1643                    let is_mono = strata_layout::is_monospace_family(node.style.font_family);
1644                    let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
1645                        &new_text,
1646                        node.style.font_size,
1647                        node.style.line_height,
1648                        None,
1649                        is_mono,
1650                        node.style.font_family,
1651                        node.style.font_weight,
1652                        node.style.font_style,
1653                    );
1654                    node.style.width = strata_style::types::Dimension::Px(w);
1655                    node.style.height = strata_style::types::Dimension::Px(h);
1656                    node.geometry.content_box.width = w;
1657                    node.geometry.content_box.height = h;
1658                    node.text = Some(new_text);
1659                    node_updated = true;
1660                    changed = true;
1661                }
1662                if node_updated {
1663                    self.layout_root.invalidate_ancestors(&binding.path);
1664                }
1665            }
1666        }
1667
1668        if changed {
1669            self.tick_frame();
1670            true
1671        } else {
1672            false
1673        }
1674    }
1675
1676    /// System cursor theme, loaded on first use. Reading cursor files from disk costs
1677    /// several milliseconds and only the MCP cursor overlay needs it.
1678    pub fn cursor_theme(&self) -> &strata_platform::CursorTheme {
1679        self.cursor_theme
1680            .get_or_init(strata_platform::CursorTheme::load_active)
1681    }
1682
1683    /// Marks only 3D viewports dirty without invalidating 2D layout or recompiling the display list.
1684    pub fn mark_viewport_3d_dirty(&mut self) {
1685        self.viewport_3d_dirty = true;
1686    }
1687
1688    /// Returns `true` when any retained 3D viewport has newer camera/geometry/overlay generations
1689    /// than what was last presented, or when `viewport_3d_dirty` was set explicitly.
1690    pub fn poll_retained_3d_dirty(&self) -> bool {
1691        if self.viewport_3d_dirty {
1692            return true;
1693        }
1694        self.tracked_retained_3d
1695            .iter()
1696            .any(|(handle, last_gens)| handle.generations() != *last_gens)
1697    }
1698
1699    /// Records the current generations of all tracked [`RetainedScene3D`] handles as presented.
1700    pub fn acknowledge_retained_3d_presented(&mut self) {
1701        self.viewport_3d_dirty = false;
1702        for (handle, last_gens) in &mut self.tracked_retained_3d {
1703            *last_gens = handle.generations();
1704        }
1705    }
1706
1707    /// Returns `true` if any `<Canvas3D>` in the current blueprint opted into uncapped presentation.
1708    pub fn has_uncapped_canvas3d(&self) -> bool {
1709        fn walk(node: &NodeBlueprint) -> bool {
1710            if let NodeBlueprint::Element {
1711                attributes,
1712                children,
1713                ..
1714            } = node
1715            {
1716                if attributes.iter().any(|a| {
1717                    matches!(
1718                        a,
1719                        strata_dom::Attribute::Property { key, value }
1720                            if key == "data-strata-uncapped" && value == "true"
1721                    )
1722                }) {
1723                    return true;
1724                }
1725                if children.iter().any(walk) {
1726                    return true;
1727                }
1728            }
1729            false
1730        }
1731        walk(&self.root_blueprint)
1732    }
1733
1734    /// Marks the compiled display list stale so the next dirty-gated compile rebuilds it.
1735    pub fn mark_paint_dirty(&mut self) {
1736        self.paint_dirty = true;
1737    }
1738
1739    /// Whether the display list is stale relative to runtime state.
1740    pub fn is_paint_dirty(&self) -> bool {
1741        self.paint_dirty
1742    }
1743
1744    /// Number of dirty-gated compiles that were skipped as unchanged.
1745    pub fn compiles_skipped(&self) -> u64 {
1746        self.compiles_skipped
1747    }
1748
1749    /// Compiles the display list only when something changed since the last compile.
1750    /// Returns true when a compile ran.
1751    pub fn compile_display_list_if_dirty(&mut self) -> bool {
1752        if !self.paint_dirty {
1753            self.compiles_skipped += 1;
1754            return false;
1755        }
1756        self.compile_display_list();
1757        true
1758    }
1759
1760    /// Generates draw commands for all computed layout rectangles using the 7-layer CSS compositor with spatial viewport scissoring.
1761    pub fn compile_display_list(&mut self) {
1762        let compile_start = std::time::Instant::now();
1763        let viewport = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
1764            Some(strata_layout::Rect::new(
1765                0.0,
1766                0.0,
1767                self.viewport_width,
1768                self.viewport_height,
1769            ))
1770        } else {
1771            None
1772        };
1773        let scrollbar_overlays = self.build_scrollbar_overlays();
1774        self.display_list =
1775            strata_render::compositor::Compositor::build_document_display_list_with_scrollbars(
1776                &self.layout_root,
1777                viewport,
1778                &scrollbar_overlays,
1779            );
1780        strata_render::compositor::Compositor::append_top_layer_portals_with_scrollbars(
1781            &self.layout_root,
1782            &mut self.display_list,
1783            viewport,
1784            &scrollbar_overlays,
1785        );
1786        self.tracked_retained_3d.clear();
1787        for cmd in &self.display_list.commands {
1788            if let strata_render::compositor::DrawCommand::DrawViewport3D { scene, .. } = cmd {
1789                if let Some(handle) = scene.retained_handle() {
1790                    self.tracked_retained_3d
1791                        .push((handle.clone(), handle.generations()));
1792                }
1793            }
1794        }
1795        self.render_active_input_caret();
1796        self.render_hover_tooltip();
1797        if self.gpu_2d_paths_enabled {
1798            self.gpu_path_pipeline
1799                .resize(self.viewport_width, self.viewport_height);
1800            self.gpu_path_pipeline
1801                .compile_frame(&self.display_list, None);
1802        }
1803        self.frame_profile.compile += compile_start.elapsed();
1804        self.paint_dirty = false;
1805
1806        static COMPILE_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1807        let frame = COMPILE_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1808        if frame < 6 || frame.is_multiple_of(120) {
1809            perf_log_ms(
1810                "compile_display_list",
1811                compile_start,
1812                format!(
1813                    "frame {} {}x{} {} commands (gpu_2d_paths={})",
1814                    frame,
1815                    self.viewport_width,
1816                    self.viewport_height,
1817                    self.display_list.commands.len(),
1818                    self.gpu_2d_paths_enabled
1819                ),
1820            );
1821        }
1822    }
1823
1824    /// Controls whether [`Self::compile_display_list`] tessellates 2D GPU path segments.
1825    /// Backends that rasterize 2D UI via Cairo software should leave this `false` unless
1826    /// `STRATA_GPU_2D=1` is active.
1827    pub fn set_gpu_2d_paths_enabled(&mut self, enabled: bool) {
1828        self.gpu_2d_paths_enabled = enabled;
1829    }
1830
1831    /// Returns whether 2D GPU path compilation is active during display-list builds.
1832    pub fn gpu_2d_paths_enabled(&self) -> bool {
1833        self.gpu_2d_paths_enabled
1834    }
1835
1836    /// Explicitly compiles 2D GPU path segments from the current display list on demand.
1837    pub fn compile_gpu_paths_now(&mut self) -> usize {
1838        self.gpu_path_pipeline
1839            .resize(self.viewport_width, self.viewport_height);
1840        self.gpu_path_pipeline
1841            .compile_frame(&self.display_list, None)
1842    }
1843
1844    /// Returns the compiled GPU path segments from the latest frame.
1845    #[inline]
1846    pub fn gpu_path_segments(&self) -> &[strata_render::gpu_path::GpuPathSegment] {
1847        &self.gpu_path_pipeline.batch.segments
1848    }
1849
1850    /// Returns the raw uniform bytes for the GPU path compute pipeline.
1851    #[inline]
1852    pub fn gpu_path_uniform_bytes(&self) -> &[u8] {
1853        self.gpu_path_pipeline.uniform_bytes()
1854    }
1855
1856    /// Processes an incoming platform event, updating viewport/scale or dispatching synthetic events.
1857    /// Returns true if a dirty layout or presentation redraw was triggered.
1858    pub fn step_event(&mut self, event: &PlatformEvent) -> bool {
1859        let input_start = std::time::Instant::now();
1860        #[cfg(feature = "devtools")]
1861        if let Some(ref mut dt) = self.devtools {
1862            if strata_devtools::DevToolsEventInterceptor::intercept(&mut dt.hud, event) {
1863                self.frame_profile.input_dispatch += input_start.elapsed();
1864                return true;
1865            }
1866        }
1867
1868        let mut needs_redraw = match event {
1869            PlatformEvent::WindowResized { width, height } => {
1870                self.viewport_width = *width as f32;
1871                self.viewport_height = *height as f32;
1872                #[cfg(feature = "devtools")]
1873                if let Some(ref mut dt) = self.devtools {
1874                    dt.hud
1875                        .update_bounds(self.viewport_width, self.viewport_height);
1876                }
1877                self.tick_frame();
1878                true
1879            }
1880            PlatformEvent::ScaleFactorChanged { scale_factor } => {
1881                self.dpr = *scale_factor;
1882                self.tick_frame();
1883                true
1884            }
1885            PlatformEvent::WindowFocused(_) => false,
1886            PlatformEvent::WindowCloseRequested => false,
1887            PlatformEvent::Scroll {
1888                delta_x, delta_y, ..
1889            } => {
1890                let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1891                let (wheel_handled, scroll_changed) = self.dispatch_smooth_scroll_action(
1892                    self.last_mouse_pos.0,
1893                    self.last_mouse_pos.1,
1894                    *delta_x,
1895                    *delta_y,
1896                );
1897                if wheel_handled {
1898                    self.rebuild_layout_tree();
1899                    true
1900                } else {
1901                    scroll_changed || tooltip_dismissed
1902                }
1903            }
1904            PlatformEvent::AnimationTick => {
1905                let scroll_changed = self.poll_smooth_scroll();
1906                let anim_changed = self.poll_animations();
1907                let caret_changed = self.poll_caret_blink();
1908                let tooltip_changed = self.poll_hover_tooltip();
1909                scroll_changed || anim_changed || caret_changed || tooltip_changed
1910            }
1911            PlatformEvent::MouseMove { x, y } => {
1912                self.last_mouse_pos = (*x, *y);
1913                let cur = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, *x, *y);
1914                self.current_cursor = cur;
1915                let hover_changed = self.update_hover(*x, *y);
1916                self.dispatch_pointer_move_action(*x, *y).needs_redraw() || hover_changed
1917            }
1918            PlatformEvent::Stylus {
1919                phase,
1920                pointer_id,
1921                tool,
1922                x,
1923                y,
1924                pressure,
1925                tilt_x,
1926                tilt_y,
1927                twist,
1928                tangential_pressure,
1929                hovering,
1930                buttons,
1931            } => {
1932                self.last_mouse_pos = (*x, *y);
1933                let hover_changed = self.update_hover(*x, *y);
1934                let dom_ev_type = match phase {
1935                    strata_platform::StylusPhase::Down => strata_dom::EventType::PointerDown,
1936                    strata_platform::StylusPhase::Move | strata_platform::StylusPhase::Hover => {
1937                        strata_dom::EventType::PointerMove
1938                    }
1939                    strata_platform::StylusPhase::Up | strata_platform::StylusPhase::Cancel => {
1940                        strata_dom::EventType::PointerUp
1941                    }
1942                };
1943                let effective_pressure = if *hovering { 0.0 } else { *pressure };
1944                let outcome = self.dispatch_bubbling_event_detailed_at(
1945                    dom_ev_type,
1946                    *x,
1947                    *y,
1948                    0,
1949                    1,
1950                    |ev| {
1951                        ev.pointer_id = *pointer_id as i32;
1952                        ev.pointer_type = tool.as_w3c_str();
1953                        ev.pressure = effective_pressure;
1954                        ev.tilt_x = *tilt_x;
1955                        ev.tilt_y = *tilt_y;
1956                        ev.twist = *twist;
1957                        ev.tangential_pressure = *tangential_pressure;
1958                        ev.buttons = *buttons;
1959                        ev.is_primary = true;
1960                    },
1961                );
1962                let dynamic_updated = self.sync_dynamic_text();
1963                if outcome.handled || dynamic_updated {
1964                    self.rebuild_layout_tree();
1965                    true
1966                } else {
1967                    hover_changed
1968                }
1969            }
1970            PlatformEvent::MouseDown { button, x, y } => {
1971                let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1972                let btn_idx = button.to_button_index();
1973                if *button == strata_platform::MouseButton::Left {
1974                    self.is_mouse_down = true;
1975                }
1976                let action = self.dispatch_pointer_down_action_with_button_and_modifiers(
1977                    *x,
1978                    *y,
1979                    btn_idx,
1980                    Default::default(),
1981                );
1982                let click_invoked = if *button != strata_platform::MouseButton::Right {
1983                    self.dispatch_mouse_click(*x, *y, btn_idx, 1)
1984                } else {
1985                    self.dispatch_context_menu(*x, *y)
1986                };
1987                let dynamic_updated = self.sync_dynamic_text();
1988                if action.needs_rebuild() || click_invoked || dynamic_updated {
1989                    self.rebuild_layout_tree();
1990                    true
1991                } else {
1992                    tooltip_dismissed || action.needs_redraw() || self.restyle_for_active_change()
1993                }
1994            }
1995            PlatformEvent::MouseUp { button, x, y } => {
1996                let btn_idx = button.to_button_index();
1997                let was_mouse_down = self.is_mouse_down;
1998                if *button == strata_platform::MouseButton::Left {
1999                    self.is_mouse_down = false;
2000                }
2001                let action = self.dispatch_pointer_up_action_with_button(*x, *y, btn_idx);
2002                if action.needs_rebuild() {
2003                    self.rebuild_layout_tree();
2004                    true
2005                } else if was_mouse_down {
2006                    action.needs_redraw() || self.restyle_for_active_change()
2007                } else {
2008                    action.needs_redraw()
2009                }
2010            }
2011            PlatformEvent::CursorLeft => {
2012                self.is_mouse_down = false;
2013                self.current_cursor = strata_platform::window::CursorIcon::Default;
2014                self.clear_hover()
2015            }
2016            PlatformEvent::KeyDown { .. }
2017            | PlatformEvent::KeyUp { .. }
2018            | PlatformEvent::ReceivedCharacter(_)
2019            | PlatformEvent::ImePreedit { .. }
2020            | PlatformEvent::ImeCommit(_) => {
2021                let tooltip_dismissed = matches!(event, PlatformEvent::KeyDown { .. })
2022                    && self.dismiss_hover_tooltip_and_repaint();
2023                let res = self.dispatch_key_event(event);
2024                let dynamic_updated = self.sync_dynamic_text();
2025                tooltip_dismissed || res.needs_redraw() || dynamic_updated
2026            }
2027            PlatformEvent::FileDrop(paths) => {
2028                let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
2029                let drop_handled = self.dispatch_file_drop(paths.clone());
2030                let dynamic_updated = self.sync_dynamic_text();
2031                if drop_handled || dynamic_updated {
2032                    self.rebuild_layout_tree();
2033                    true
2034                } else {
2035                    tooltip_dismissed
2036                }
2037            }
2038            _ => false,
2039        };
2040
2041        if self.poll_dom_mutations(None) {
2042            needs_redraw = true;
2043        }
2044
2045        if needs_redraw {
2046            self.paint_dirty = true;
2047        }
2048        self.frame_profile.input_dispatch += input_start.elapsed();
2049        needs_redraw
2050    }
2051
2052    /// Number of full layout computations performed by this runtime.
2053    pub fn layout_computations(&self) -> u64 {
2054        self.layout_computations
2055    }
2056
2057    /// True when the most recent `update_view` reconciled the existing layout tree in place.
2058    pub fn last_update_reconciled(&self) -> bool {
2059        self.last_update_reconciled
2060    }
2061
2062    /// Per-update reconciliation statistics (reused subtrees vs rebuilt nodes).
2063    pub fn last_reconcile_stats(&self) -> ReconcileStats {
2064        self.last_reconcile_stats
2065    }
2066
2067    /// Reason the most recent `update_view` bailed out of incremental reconciliation, if any.
2068    pub fn last_reconcile_bailout(&self) -> Option<&str> {
2069        self.last_reconcile_bailout.as_deref()
2070    }
2071
2072    /// True when the most recent paint-only hover update succeeded via `restyle_hover_subtrees_fast`.
2073    pub fn last_hover_fast_path_used(&self) -> bool {
2074        self.last_hover_fast_path_used
2075    }
2076
2077    /// Reason the most recent paint-only hover update bailed out of `restyle_hover_subtrees_fast`, if any.
2078    pub fn last_hover_fast_path_bailout(&self) -> Option<&str> {
2079        self.last_hover_fast_path_bailout.as_deref()
2080    }
2081
2082    /// Cumulative number of full layout tree rebuilds performed by this runtime.
2083    pub fn full_rebuilds_count(&self) -> u64 {
2084        self.full_rebuilds_count
2085    }
2086
2087    /// Cumulative number of incremental reconciled updates performed by this runtime.
2088    pub fn reconciled_updates_count(&self) -> u64 {
2089        self.reconciled_updates_count
2090    }
2091
2092    /// Structured reason attributing why the latest frame ran work.
2093    pub fn last_rebuild_reason(&self) -> &RebuildReason {
2094        &self.last_rebuild_reason
2095    }
2096
2097    /// Records the primary reason why the current frame was triggered.
2098    pub fn set_rebuild_reason(&mut self, reason: RebuildReason) {
2099        self.last_rebuild_reason = reason;
2100    }
2101
2102    /// Phase timings accumulated since the last presented frame.
2103    pub fn frame_profile(&self) -> FrameProfile {
2104        self.frame_profile
2105    }
2106
2107    /// Most recent completed per-frame telemetry record (for host HUDs & profiling overlays).
2108    pub fn last_frame_profile(&self) -> Option<&FrameProfileRecord> {
2109        self.profile_history.last()
2110    }
2111
2112    /// Rolling p50/p95/p99 performance distribution and cache hit summary over recent frames.
2113    pub fn perf_profile_summary(&self) -> PerfProfileSummary {
2114        self.profile_history.summary(
2115            self.frame_count,
2116            self.full_rebuilds_count,
2117            self.reconciled_updates_count,
2118        )
2119    }
2120
2121    /// Registers an observer called with each completed [`FrameProfile`].
2122    pub fn set_frame_profile_hook(&mut self, hook: Option<Box<dyn FnMut(&FrameProfile)>>) {
2123        self.frame_profile_hook = hook.map(FrameProfileHook);
2124    }
2125
2126    /// Adds time spent dispatching platform or MCP input events.
2127    pub fn record_input_dispatch_time(&mut self, elapsed: std::time::Duration) {
2128        self.frame_profile.input_dispatch += elapsed;
2129    }
2130
2131    /// Adds time spent draining reactive signals and flushing subscribers.
2132    pub fn record_signal_drain_time(&mut self, elapsed: std::time::Duration) {
2133        self.frame_profile.signal_drain += elapsed;
2134    }
2135
2136    /// Adds time spent evaluating the host RSX view closure.
2137    pub fn record_view_render_time(&mut self, elapsed: std::time::Duration) {
2138        self.frame_profile.view_render += elapsed;
2139    }
2140
2141    /// Adds time spent rasterizing, for presenting backends that rasterize outside the runtime.
2142    pub fn record_raster_time(&mut self, elapsed: std::time::Duration) {
2143        self.frame_profile.raster += elapsed;
2144    }
2145
2146    /// Adds CPU time spent submitting wgpu 3D passes and compositing commands.
2147    pub fn record_wgpu_3d_submit_time(&mut self, elapsed: std::time::Duration) {
2148        self.frame_profile.wgpu_3d_submit += elapsed;
2149    }
2150
2151    /// Adds time spent presenting, for backends that present outside the runtime.
2152    pub fn record_present_time(&mut self, elapsed: std::time::Duration) {
2153        self.frame_profile.present += elapsed;
2154    }
2155
2156    /// Computes a real Cumulative Layout Shift (CLS) score against the previous frame's
2157    /// top-level layout rectangles and updates `self.prev_layout_cls_rects`.
2158    fn compute_real_layout_shift_score(&mut self) -> f32 {
2159        let mut cur_rects: Vec<(f32, f32, f32, f32)> = Vec::new();
2160        for child in self.layout_root.children.iter().take(32) {
2161            let b = child.geometry.border_box;
2162            cur_rects.push((b.x, b.y, b.width, b.height));
2163        }
2164        let mut max_shift = 0.0f32;
2165        let vw = self.viewport_width.max(1.0);
2166        let vh = self.viewport_height.max(1.0);
2167        let max_dim = vw.max(vh);
2168        let vp_area = (vw * vh).max(1.0);
2169        for (prev, cur) in self.prev_layout_cls_rects.iter().zip(cur_rects.iter()) {
2170            let dx = (cur.0 - prev.0).abs();
2171            let dy = (cur.1 - prev.1).abs();
2172            if dx > 0.5 || dy > 0.5 {
2173                let dist = (dx.max(dy) / max_dim).clamp(0.0, 1.0);
2174                let impact = ((prev.2 * prev.3).max(cur.2 * cur.3) / vp_area).clamp(0.0, 1.0);
2175                max_shift = max_shift.max(impact * dist);
2176            }
2177        }
2178        self.prev_layout_cls_rects = cur_rects;
2179        max_shift
2180    }
2181
2182    /// Publishes the accumulated profile to the hook and starts a fresh frame.
2183    /// Returns the profile that was completed.
2184    pub fn finish_frame_profile(&mut self) -> FrameProfile {
2185        let done = std::mem::take(&mut self.frame_profile);
2186        if let Some(hook) = self.frame_profile_hook.as_mut() {
2187            (hook.0)(&done);
2188        }
2189        done
2190    }
2191
2192    /// Finalizes a presented frame: snapshots all real monotonic CPU phase timings, GPU hardware
2193    /// timestamp queries, 64x64 tile cache stats, Scene3D offscreen cache stats, text/glyph cache
2194    /// hit rate, heap allocation deltas, and DevTools live HUD / Time-Travel / Perfetto state.
2195    pub fn finalize_frame_telemetry(&mut self, outcome: &'static str) -> FrameProfileRecord {
2196        let gpu_tel = strata_platform::gtk_last_gpu_telemetry();
2197        let (tiles_dirty, tiles_total) = strata_platform::gtk_last_tile_cache_stats();
2198        let tile_cache_hit_pct = if tiles_total > 0 {
2199            ((tiles_total.saturating_sub(tiles_dirty)) as f32 / tiles_total as f32) * 100.0
2200        } else {
2201            100.0
2202        };
2203        let s3d_total = gpu_tel.scene3d_cache_hits + gpu_tel.scene3d_cache_misses;
2204        let scene3d_cache_hit_pct = if s3d_total > 0 {
2205            (gpu_tel.scene3d_cache_hits as f32 / s3d_total as f32) * 100.0
2206        } else {
2207            100.0
2208        };
2209        let (text_hits, text_misses) = strata_layout::text_measure_cache_stats();
2210        let text_total = text_hits + text_misses;
2211        let glyph_atlas_hit_pct = if text_total > 0 {
2212            (text_hits as f32 / text_total as f32) * 100.0
2213        } else {
2214            100.0
2215        };
2216
2217        self.frame_profile.gpu_3d_us = gpu_tel
2218            .gpu_shadow_pass_us
2219            .saturating_add(gpu_tel.gpu_3d_pass_us);
2220        self.frame_profile.gpu_2d_overlay_us = gpu_tel.gpu_2d_overlay_pass_us;
2221        self.frame_profile.gpu_timestamps_valid = gpu_tel.gpu_timestamps_supported;
2222
2223        let done = self.finish_frame_profile();
2224        let cls_score = self.compute_real_layout_shift_score();
2225        let timestamp_us = self.runtime_epoch.elapsed().as_micros() as u64;
2226        let (heap_alloc_count, heap_alloc_bytes) = profile::take_frame_heap_alloc_delta();
2227
2228        let dom_nodes = perf_count_blueprint_nodes(&self.root_blueprint);
2229        let layout_nodes = perf_count_layout_nodes(&self.layout_root);
2230        let display_cmds = self.display_list.len();
2231
2232        let reconcile_us = if !done.reconcile.is_zero() {
2233            done.reconcile.as_micros() as u32
2234        } else {
2235            done.rebuild.as_micros() as u32
2236        };
2237        let style_cascade_us = done.style_cascade.as_micros() as u32;
2238        let input_dispatch_us = done.input_dispatch.as_micros() as u32;
2239        let signal_drain_us = done.signal_drain.as_micros() as u32;
2240        let view_render_us = done.view_render.as_micros() as u32;
2241        let layout_us = done.layout.as_micros() as u32;
2242        let display_list_build_us = done.compile.as_micros() as u32;
2243        let raster_us = done.raster.as_micros() as u32;
2244        let wgpu_3d_submit_us = done.wgpu_3d_submit.as_micros() as u32;
2245        let present_us = done.present.as_micros() as u32;
2246        let total_cpu_us = done.total().as_micros() as u32;
2247
2248        let reason_str = self.last_rebuild_reason.to_string();
2249        let record = FrameProfileRecord {
2250            frame_index: self.frame_count,
2251            timestamp_us,
2252            rebuild_reason: reason_str.clone(),
2253            outcome: outcome.to_string(),
2254            input_dispatch_us,
2255            signal_drain_us,
2256            view_render_us,
2257            reconcile_us,
2258            style_cascade_us,
2259            layout_us,
2260            display_list_build_us,
2261            raster_us,
2262            wgpu_3d_submit_us,
2263            present_us,
2264            total_cpu_us,
2265            gpu_3d_us: done.gpu_3d_us,
2266            gpu_2d_overlay_us: done.gpu_2d_overlay_us,
2267            gpu_timestamps_valid: done.gpu_timestamps_valid,
2268            dom_nodes: dom_nodes as u32,
2269            layout_nodes: layout_nodes as u32,
2270            display_cmds: display_cmds as u32,
2271            tiles_dirty,
2272            tiles_total,
2273            tile_cache_hit_pct,
2274            reconciled_subtrees: self.last_reconcile_stats.reused_subtrees,
2275            rebuilt_nodes: self.last_reconcile_stats.rebuilt_nodes,
2276            full_rebuilds: self.full_rebuilds_count,
2277            reconciled: self.last_update_reconciled,
2278            hover_fast_path_used: self.last_hover_fast_path_used,
2279            hover_fast_path_bailout: self.last_hover_fast_path_bailout.clone(),
2280            reconcile_bailout: self.last_reconcile_bailout.clone(),
2281            scene3d_cache_hits: gpu_tel.scene3d_cache_hits,
2282            scene3d_cache_misses: gpu_tel.scene3d_cache_misses,
2283            scene3d_cache_hit_pct,
2284            glyph_atlas_hit_pct,
2285            gpu_memory_bytes: gpu_tel.gpu_memory_bytes,
2286            heap_alloc_count,
2287            heap_alloc_bytes,
2288            layout_shift_score: cls_score,
2289        };
2290        self.profile_history.push(record.clone());
2291
2292        #[cfg(feature = "devtools")]
2293        if let Some(ref mut dt) = self.devtools {
2294            let ui_tid = strata_devtools::current_thread_id_u64();
2295            let gpu_tid = ui_tid.wrapping_add(1).max(2);
2296            let gpu_total_hw = gpu_tel
2297                .gpu_shadow_pass_us
2298                .saturating_add(gpu_tel.gpu_3d_pass_us)
2299                .saturating_add(gpu_tel.gpu_2d_overlay_pass_us);
2300            let sample = strata_devtools::FrameTimingSample {
2301                frame_index: self.frame_count,
2302                timestamp_us,
2303                pid: std::process::id(),
2304                ui_thread_id: ui_tid,
2305                worker_thread_id: 0,
2306                gpu_thread_id: gpu_tid,
2307                vsync_wait_us: 0,
2308                input_dispatch_us,
2309                signal_drain_us,
2310                view_render_us,
2311                parallel_reconcile_us: reconcile_us,
2312                style_cascade_us,
2313                layout_solve_us: layout_us,
2314                display_list_build_us,
2315                raster_2d_us: raster_us,
2316                gpu_submit_us: wgpu_3d_submit_us,
2317                present_us,
2318                gpu_raster_duration_us: if gpu_tel.gpu_timestamps_supported {
2319                    gpu_total_hw
2320                } else {
2321                    raster_us.saturating_add(wgpu_3d_submit_us)
2322                },
2323                gpu_shadow_pass_us: gpu_tel.gpu_shadow_pass_us,
2324                gpu_3d_pass_us: gpu_tel.gpu_3d_pass_us,
2325                gpu_2d_overlay_pass_us: gpu_tel.gpu_2d_overlay_pass_us,
2326                gpu_timestamps_valid: gpu_tel.gpu_timestamps_supported,
2327                total_cpu_frame_us: total_cpu_us,
2328                frame_budget_us: dt.profiler.frame_budget_us(),
2329                layout_shift_score: cls_score,
2330            };
2331            dt.profiler.record_sample(sample);
2332
2333            let react_snap = strata_dom::reactive_telemetry_snapshot();
2334            let arena_est_bytes = dom_nodes
2335                .saturating_mul(std::mem::size_of::<NodeBlueprint>())
2336                .saturating_add(layout_nodes.saturating_mul(std::mem::size_of::<strata_layout::LayoutNode>()))
2337                .saturating_add(display_cmds.saturating_mul(std::mem::size_of::<strata_render::DrawCommand>()));
2338            let arena_cap_bytes = (arena_est_bytes.max(64 * 1024)).next_power_of_two();
2339            dt.arena_inspector
2340                .record_sample(strata_devtools::ArenaTelemetrySample::new(
2341                    0,
2342                    arena_est_bytes,
2343                    arena_cap_bytes,
2344                    arena_est_bytes,
2345                    self.frame_count,
2346                ));
2347            if heap_alloc_bytes > 0 {
2348                dt.heap_tracker.record_allocation(heap_alloc_bytes as usize);
2349            }
2350            dt.live_telemetry = strata_devtools::HudLiveTelemetry {
2351                reactive_active_signals: react_snap.active_signals,
2352                reactive_active_subscribers: react_snap.active_subscribers,
2353                reactive_total_reads: react_snap.total_reads,
2354                reactive_total_writes: react_snap.total_writes,
2355                reactive_total_flushes: react_snap.total_flushes,
2356                reactive_cycle_guard_trips: react_snap.cycle_guard_trips,
2357                last_rebuild_reason: reason_str.clone(),
2358                dirty_signal_names: react_snap.dirty_signal_names,
2359                top_signals: react_snap
2360                    .signals
2361                    .iter()
2362                    .take(8)
2363                    .map(|s| (s.name.clone(), s.write_count, s.read_count, s.subscriber_count))
2364                    .collect(),
2365                dom_node_count: dom_nodes,
2366                layout_node_count: layout_nodes,
2367                display_cmd_count: display_cmds,
2368                arena_allocated_bytes: arena_est_bytes,
2369                arena_capacity_bytes: arena_cap_bytes,
2370                heap_alloc_bytes,
2371                heap_alloc_count,
2372                gpu_memory_bytes: gpu_tel.gpu_memory_bytes,
2373                tiles_dirty,
2374                tiles_total,
2375                tile_cache_hit_pct,
2376                scene3d_cache_hit_pct,
2377                glyph_cache_hit_pct: glyph_atlas_hit_pct,
2378                reconciled_updates: self.reconciled_updates_count,
2379                full_rebuilds: self.full_rebuilds_count,
2380            };
2381
2382            if outcome == "Dirty" || dt.time_travel.is_empty() {
2383                let mut ir_hash: u64 = 0xcbf2_9ce4_8422_2325;
2384                ir_hash ^= (dom_nodes as u64).wrapping_mul(0x100_0000_01b3);
2385                ir_hash ^= (layout_nodes as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
2386                ir_hash ^= (display_cmds as u64).wrapping_mul(0x517c_c1b7_2722_0a95);
2387                ir_hash ^= self.layout_computations;
2388                let sig_values: Vec<(usize, String)> = react_snap
2389                    .signals
2390                    .iter()
2391                    .take(16)
2392                    .map(|s| {
2393                        (
2394                            s.signal_id,
2395                            format!("{}:w{}r{}", s.name, s.write_count, s.read_count),
2396                        )
2397                    })
2398                    .collect();
2399                dt.time_travel
2400                    .record_snapshot(timestamp_us, reason_str, sig_values, ir_hash);
2401            }
2402            dt.cdp_dispatcher.update_from_ir(
2403                &self.ir_graph,
2404                &self.base_node_styles,
2405                self.frame_count,
2406                self.layout_computations,
2407            );
2408        }
2409
2410        record
2411    }
2412
2413    /// Renders the current frame and presents it to the given surface presenter via the swapchain compositor.
2414    pub fn render_frame<P: SurfacePresenter>(
2415        &mut self,
2416        compositor: &mut SwapchainCompositor,
2417        presenter: &mut P,
2418        force_redraw: bool,
2419    ) -> Result<bool, PresentError> {
2420        let retained_3d_dirty = self.poll_retained_3d_dirty();
2421        let did_dirty_tick = self.paint_dirty || self.frame_count == 0 || force_redraw;
2422        if did_dirty_tick {
2423            self.tick_frame();
2424        } else {
2425            self.compiles_skipped += 1;
2426            if retained_3d_dirty {
2427                self.frame_count += 1;
2428            }
2429        }
2430
2431        #[cfg(feature = "devtools")]
2432        if let Some(ref mut dt) = self.devtools {
2433            if dt.hud.state.is_visible {
2434                dt.render_hud_overlay(&mut self.display_list);
2435            }
2436        }
2437
2438        let present_start = std::time::Instant::now();
2439        let res = compositor.render_and_present(
2440            &self.display_list,
2441            presenter,
2442            force_redraw || retained_3d_dirty,
2443        );
2444        self.acknowledge_retained_3d_presented();
2445        self.frame_profile.present += present_start.elapsed();
2446
2447        let outcome = if did_dirty_tick {
2448            "Dirty"
2449        } else if retained_3d_dirty {
2450            "RepaintCanvas3D"
2451        } else {
2452            "Clean"
2453        };
2454        self.finalize_frame_telemetry(outcome);
2455
2456        res
2457    }
2458
2459    #[cfg(feature = "devtools")]
2460    /// Initializes and mounts the in-process DevTools diagnostics suite.
2461    pub fn enable_devtools(&mut self) -> &mut strata_devtools::DevTools {
2462        if self.devtools.is_none() {
2463            let mut dt = strata_devtools::DevTools::new();
2464            dt.hud
2465                .update_bounds(self.viewport_width, self.viewport_height);
2466            self.devtools = Some(dt);
2467        }
2468        self.devtools.as_mut().unwrap()
2469    }
2470
2471    #[cfg(feature = "devtools")]
2472    /// Returns reference to DevTools diagnostics suite if active.
2473    pub fn devtools(&self) -> Option<&strata_devtools::DevTools> {
2474        self.devtools.as_ref()
2475    }
2476
2477    #[cfg(feature = "devtools")]
2478    /// Returns mutable reference to DevTools diagnostics suite if active.
2479    pub fn devtools_mut(&mut self) -> Option<&mut strata_devtools::DevTools> {
2480        self.devtools.as_mut()
2481    }
2482
2483    /// Runs the reactive event loop against a live platform window and surface presenter.
2484    pub fn run_with_window<W, E, P>(
2485        &mut self,
2486        window: &mut W,
2487        event_loop: &mut E,
2488        compositor: &mut SwapchainCompositor,
2489        presenter: &mut P,
2490    ) where
2491        W: PlatformWindow,
2492        E: EventLoop,
2493        P: SurfacePresenter,
2494    {
2495        // Initial frame presentation
2496        let _ = self.render_frame(compositor, presenter, true);
2497
2498        event_loop.run(|event, control| {
2499            match event {
2500                PlatformEvent::WindowResized { width, height } => {
2501                    compositor.resize(width, height, self.dpr);
2502                    let _ = presenter.resize(width, height);
2503                }
2504                PlatformEvent::ScaleFactorChanged { scale_factor } => {
2505                    compositor.resize(
2506                        self.viewport_width as u32,
2507                        self.viewport_height as u32,
2508                        scale_factor,
2509                    );
2510                }
2511                PlatformEvent::WindowCloseRequested => {
2512                    *control = EventLoopControl::Exit;
2513                    return;
2514                }
2515                _ => {}
2516            }
2517
2518            let needs_redraw = self.step_event(&event);
2519            window.set_cursor(self.current_cursor());
2520
2521            if needs_redraw || window.is_redraw_requested() {
2522                let _ = self.render_frame(compositor, presenter, false);
2523            }
2524
2525            // Power-saving sleep mode: if no events pending, wait for next input
2526            *control = EventLoopControl::Wait;
2527        });
2528    }
2529
2530    /// Rasterizes the current application frame to an offscreen headless FrameBuffer.
2531    pub fn render_to_framebuffer(&mut self) -> strata_render::rasterizer::FrameBuffer {
2532        self.tick_frame();
2533        let width = (self.viewport_width * self.dpr).max(1.0).ceil() as usize;
2534        let height = (self.viewport_height * self.dpr).max(1.0).ceil() as usize;
2535        let mut fb = strata_render::rasterizer::FrameBuffer::new(width, height);
2536        fb.execute_display_list(&self.display_list);
2537        fb
2538    }
2539
2540    /// Captures a headless screenshot of the current application state and writes it to a PNG file.
2541    pub fn export_png<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), String> {
2542        let fb = self.render_to_framebuffer();
2543        fb.export_png(path).map_err(|e| e.to_string())
2544    }
2545
2546    #[cfg(feature = "pdf")]
2547    /// Compiles the current `AppRuntime` vector [`DisplayList`] directly into a PDF 1.7 byte buffer.
2548    pub fn export_pdf_bytes(&mut self, options: &strata_render::PdfExportOptions) -> Vec<u8> {
2549        self.compile_display_list();
2550        strata_render::export_display_list_to_pdf(
2551            &self.display_list,
2552            self.viewport_width,
2553            self.viewport_height,
2554            options,
2555        )
2556    }
2557
2558    #[cfg(feature = "pdf")]
2559    /// Exports the current `AppRuntime` UI directly to a lossless Vector PDF 1.7 file on disk.
2560    pub fn export_pdf<P: AsRef<std::path::Path>>(
2561        &mut self,
2562        path: P,
2563        options: &strata_render::PdfExportOptions,
2564    ) -> Result<(), String> {
2565        let bytes = self.export_pdf_bytes(options);
2566        std::fs::write(path, bytes).map_err(|e| e.to_string())
2567    }
2568
2569    #[cfg(feature = "devtools")]
2570    /// Synchronizes the current live DOM tree, computed styles, and frame metrics to a Chrome DevTools dispatcher.
2571    pub fn sync_to_devtools(&self, dispatcher: &strata_devtools::cdp::CdpDispatcher) {
2572        dispatcher.update_from_ir(
2573            &self.ir_graph,
2574            &self.base_node_styles,
2575            self.frame_count,
2576            self.layout_computations,
2577        );
2578    }
2579}