1use 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 platforms;
19pub mod types;
20
21mod a11y;
22mod animation;
23mod canvas3d;
24pub mod dom_hydration;
25mod events;
26mod hit_test;
27mod hover;
28mod image;
29mod input_hit_test;
30mod layout_tree;
31mod mcp;
32mod profile;
33mod scroll;
34mod scrollbar;
35mod selection;
36pub mod spatial;
37mod tailwind;
38pub mod test_support;
39
40pub use app::*;
41pub use dom_hydration::*;
42pub use edit::*;
43#[cfg(feature = "hot-reload")]
44pub use hmr_bridge::*;
45pub(crate) use image::*;
46pub use launch::*;
47pub use platforms::*;
48pub use profile::{
49 take_frame_heap_alloc_delta, total_heap_alloc_stats, FrameProfile, FrameProfileHistory,
50 FrameProfileHook, FrameProfileRecord, PerfPercentileStats, PerfProfileSummary,
51 ProfilingAllocator,
52};
53pub use spatial::*;
54pub use test_support::{MatchMode, NodeQuery};
55pub use types::*;
56
57#[derive(Debug)]
59pub struct AppRuntime {
60 pub root_blueprint: NodeBlueprint,
61 pub ir_graph: strata_dom::UiIrGraph,
62 pub layout_root: LayoutNode,
63 pub display_list: DisplayList,
64 pub spatial_index: SpatialIndex,
65 pub viewport_width: f32,
66 pub viewport_height: f32,
67 pub dpr: f32,
68 pub frame_count: u64,
69 pub active_focus: Option<ActiveInput>,
70 pub input_states: std::collections::HashMap<String, strata_dom::text_input::TextInputState>,
71 pub caret_blink_epoch: std::time::Instant,
72 pub last_caret_blink_state: bool,
73 pub current_cursor: strata_platform::window::CursorIcon,
74 pub drag_selection_active: bool,
75 pub last_click_info: Option<(std::time::Instant, f32, f32, usize)>,
76 pub pending_window_drag: Option<(f32, f32)>,
78 pub last_drag_click: Option<(std::time::Instant, f32, f32)>,
80 pub current_hover_path: Option<Vec<usize>>,
82 pub current_focus_path: Option<Vec<usize>>,
84 pub is_mouse_down: bool,
86 pub is_dark_mode: bool,
88 pub last_mouse_pos: (f32, f32),
90 pub hover_tooltip_text: Option<String>,
92 pub hover_tooltip_path: Option<Vec<usize>>,
94 pub hover_tooltip_anchor: (f32, f32),
96 pub hover_tooltip_since: Option<std::time::Instant>,
98 pub hover_tooltip_visible: bool,
100 pub hover_tooltip_delay: std::time::Duration,
102 pub hover_tooltip_style: strata_platform::HoverTooltipStyle,
104 pub scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
106 pub scroll_offsets_by_id: std::collections::HashMap<String, (f32, f32)>,
108 pub active_scrollbars: Vec<ActiveScrollbar>,
110 pub scrollbar_drag: Option<ScrollbarDrag>,
112 pub active_smooth_scroll: Option<SmoothScrollTracker>,
114 pub last_scroll_interaction: Option<std::time::Instant>,
116 pub applied_scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
118 pub applied_portal_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
120 pub(crate) has_anchored_portals: bool,
122 pub runtime_start_epoch: std::time::Instant,
124 pub transition_manager: strata_style::transition::TransitionManager,
126 pub animation_manager: strata_style::animation::AnimationManager,
128 pub base_node_styles: std::collections::HashMap<u64, ComputedStyle>,
130 pub previous_node_styles: std::collections::HashMap<u64, ComputedStyle>,
132 pub previous_node_sizes: std::collections::HashMap<u64, (f32, f32)>,
135 pub node_paths: std::collections::HashMap<u64, Vec<usize>>,
137 pub path_node_ids: std::collections::HashMap<Vec<usize>, u64>,
139 pub view_transition_manager: crate::view_transition::ViewTransitionManager,
141 pub had_active_animations: bool,
143 pub gpu_path_pipeline: strata_render::GpuPathPipeline,
145 pub(crate) layout_computations: u64,
147 pub(crate) hover_paint_only: bool,
149 pub mcp_cursor: Option<strata_platform::McpCursorState>,
151 pub(crate) cursor_theme: std::sync::OnceLock<strata_platform::CursorTheme>,
153 pub a11y_bridge: strata_a11y::A11yBridge,
155 pub a11y_tree: Option<strata_a11y::A11yTree>,
157 pub a11y_updates_count: u64,
159 pub dynamic_text_bindings: Vec<DynamicTextBinding>,
161 pub dom_mutation_receiver: Option<std::sync::mpsc::Receiver<strata_js::DomMutationRecord>>,
163 #[cfg(feature = "devtools")]
164 pub devtools: Option<strata_devtools::DevTools>,
166 pub csd_controller: strata_platform::CsdController,
168 pub(crate) frame_profile: FrameProfile,
170 pub(crate) paint_dirty: bool,
172 pub(crate) viewport_3d_dirty: bool,
174 pub(crate) tracked_retained_3d: Vec<(strata_render::scene3d::RetainedScene3D, (u64, u64, u64))>,
176 pub(crate) compiles_skipped: u64,
178 pub(crate) frame_profile_hook: Option<FrameProfileHook>,
180 pub(crate) cached_stylesheets: Vec<std::sync::Arc<strata_style::StyleSheet>>,
182 pub(crate) stylesheet_index: StylesheetSelectorIndex,
184 pub(crate) cached_root_inherited_style: Option<ComputedStyle>,
186 pub(crate) gpu_2d_paths_enabled: bool,
190 pub pointer_capture_target: Option<(Vec<usize>, bool)>,
192 pub(crate) has_resize_listeners: bool,
194 pub observed_element_sizes: std::collections::HashMap<u64, (f32, f32)>,
196 pub(crate) last_pointer_pos: Option<(f32, f32)>,
198 pub(crate) pending_cursor_warp: Option<(f32, f32)>,
200 pub(crate) last_update_reconciled: bool,
202 pub(crate) last_reconcile_stats: ReconcileStats,
204 pub(crate) last_reconcile_bailout: Option<String>,
206 pub(crate) last_hover_fast_path_used: bool,
208 pub(crate) last_hover_fast_path_bailout: Option<String>,
210 pub(crate) full_rebuilds_count: u64,
212 pub(crate) reconciled_updates_count: u64,
214 pub(crate) last_rebuild_reason: RebuildReason,
216 pub(crate) runtime_epoch: std::time::Instant,
218 pub(crate) profile_history: FrameProfileHistory,
220 pub(crate) prev_layout_cls_rects: Vec<(f32, f32, f32, f32)>,
222 pub(crate) active_dom_drag: Option<ActiveDomDrag>,
224}
225
226pub(crate) fn perf_logging_enabled() -> bool {
228 static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
229 *ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
230}
231
232pub(crate) fn perf_log_ms(label: &str, start: std::time::Instant, detail: impl std::fmt::Display) {
234 if perf_logging_enabled() {
235 eprintln!(
236 "[perf] {}: {:.3} ms ({})",
237 label,
238 start.elapsed().as_secs_f64() * 1000.0,
239 detail
240 );
241 }
242}
243
244pub(crate) fn perf_count_layout_nodes(node: &strata_layout::LayoutNode) -> usize {
245 let mut count = 0;
246 let mut stack = vec![node];
247 while let Some(n) = stack.pop() {
248 count += 1;
249 for child in &n.children {
250 stack.push(child);
251 }
252 }
253 count
254}
255
256pub(crate) fn perf_count_blueprint_nodes(node: &NodeBlueprint) -> usize {
257 let mut count = 0;
258 let mut stack = vec![node];
259 while let Some(n) = stack.pop() {
260 count += 1;
261 match n {
262 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
263 for child in children {
264 stack.push(child);
265 }
266 }
267 NodeBlueprint::Text(_) | NodeBlueprint::DynamicText(_) | NodeBlueprint::Empty => {}
268 }
269 }
270 count
271}
272
273impl AppRuntime {
274 pub fn from_root<F: FnOnce() -> View>(
281 root: F,
282 viewport_width: f32,
283 viewport_height: f32,
284 dpr: f32,
285 ) -> Self {
286 let root_view = strata_dom::with_root_component_scope(root);
287 Self::new(root_view, viewport_width, viewport_height, dpr)
288 }
289
290 pub fn new(root_view: View, viewport_width: f32, viewport_height: f32, dpr: f32) -> Self {
292 static REGISTER_JS_FETCH: std::sync::Once = std::sync::Once::new();
293 REGISTER_JS_FETCH.call_once(|| {
294 strata_js::web::set_global_fetch_handler(std::sync::Arc::new(|req| {
295 let mut web_req = strata_web_api::fetch::RequestInit {
296 method: req.method,
297 ..Default::default()
298 };
299 for (k, v) in req.headers {
300 web_req.headers.set(&k, &v);
301 }
302 if let Some(body) = req.body {
303 web_req = web_req.body(body);
304 }
305 let resp = strata_web_api::fetch::fetch(&req.url, Some(web_req))
306 .map_err(|e| e.to_string())?;
307 Ok(strata_js::web::FetchResponse {
308 status: resp.status,
309 status_text: resp.status_text.clone(),
310 headers: resp
311 .headers
312 .all_entries()
313 .into_iter()
314 .map(|(k, v)| (k.to_string(), v.to_string()))
315 .collect(),
316 body: resp.bytes().to_vec(),
317 })
318 }));
319 });
320
321 #[cfg(target_os = "linux")]
322 strata_platform::init_pango_text_measurement();
323
324 let mut root_blueprint = root_view.root.flatten_fragments();
325 root_blueprint.ensure_entity_ids();
326 let mut ir_graph = Self::build_ir_graph(&root_blueprint);
327
328 let build_start = std::time::Instant::now();
329 let mut layout_root = Self::build_layout_tree(&root_blueprint);
330 if perf_logging_enabled() {
331 perf_log_ms(
332 "build_layout_tree_initial",
333 build_start,
334 format!("{} layout nodes", perf_count_layout_nodes(&layout_root)),
335 );
336 }
337
338 let compute_start = std::time::Instant::now();
339 layout_root.compute_layout(viewport_width, viewport_height);
340 Self::sync_layout_to_ir(&layout_root, &mut ir_graph);
341 let mut spatial_index = SpatialIndex::new();
342 spatial_index.rebuild(&root_blueprint, &layout_root);
343 if perf_logging_enabled() {
344 perf_log_ms(
345 "compute_layout_initial",
346 compute_start,
347 format!("{}x{}", viewport_width, viewport_height),
348 );
349 }
350
351 let mut dynamic_text_bindings = Vec::new();
352 let mut path_buf = Vec::new();
353 Self::collect_dynamic_text_bindings(
354 &root_blueprint,
355 &mut path_buf,
356 &mut dynamic_text_bindings,
357 );
358
359 let mut runtime = Self {
360 root_blueprint,
361 ir_graph,
362 layout_root,
363 display_list: DisplayList::new(),
364 spatial_index,
365 viewport_width,
366 viewport_height,
367 dpr,
368 frame_count: 0,
369 active_focus: None,
370 input_states: std::collections::HashMap::new(),
371 caret_blink_epoch: std::time::Instant::now(),
372 last_caret_blink_state: true,
373 current_cursor: strata_platform::window::CursorIcon::Default,
374 drag_selection_active: false,
375 last_click_info: None,
376 pending_window_drag: None,
377 last_drag_click: None,
378 current_hover_path: None,
379 current_focus_path: None,
380 is_mouse_down: false,
381 is_dark_mode: false,
382 last_mouse_pos: (0.0, 0.0),
383 hover_tooltip_text: None,
384 hover_tooltip_path: None,
385 hover_tooltip_anchor: (0.0, 0.0),
386 hover_tooltip_since: None,
387 hover_tooltip_visible: false,
388 hover_tooltip_delay: std::time::Duration::from_millis(450),
389 hover_tooltip_style: strata_platform::HoverTooltipStyle::default(),
390 scroll_offsets: std::collections::HashMap::new(),
391 scroll_offsets_by_id: std::collections::HashMap::new(),
392 active_scrollbars: Vec::new(),
393 scrollbar_drag: None,
394 active_smooth_scroll: None,
395 last_scroll_interaction: None,
396 applied_scroll_offsets: std::collections::HashMap::new(),
397 applied_portal_offsets: std::collections::HashMap::new(),
398 has_anchored_portals: false,
399 runtime_start_epoch: std::time::Instant::now(),
400 transition_manager: strata_style::transition::TransitionManager::new(),
401 animation_manager: strata_style::animation::AnimationManager::new(),
402 base_node_styles: std::collections::HashMap::new(),
403 previous_node_styles: std::collections::HashMap::new(),
404 previous_node_sizes: std::collections::HashMap::new(),
405 node_paths: std::collections::HashMap::new(),
406 path_node_ids: std::collections::HashMap::new(),
407 view_transition_manager: crate::view_transition::ViewTransitionManager::new(),
408 had_active_animations: false,
409 gpu_path_pipeline: strata_render::GpuPathPipeline::new(viewport_width, viewport_height),
410 layout_computations: 1,
411 hover_paint_only: false,
412 mcp_cursor: None,
413 cursor_theme: std::sync::OnceLock::new(),
414 a11y_bridge: strata_a11y::A11yBridge::new(),
415 a11y_tree: None,
416 a11y_updates_count: 0,
417 dynamic_text_bindings,
418 dom_mutation_receiver: None,
419 #[cfg(feature = "devtools")]
420 devtools: None,
421 csd_controller: strata_platform::CsdController::default(),
422 frame_profile: FrameProfile::default(),
423 paint_dirty: true,
424 viewport_3d_dirty: false,
425 tracked_retained_3d: Vec::new(),
426 compiles_skipped: 0,
427 frame_profile_hook: None,
428 cached_stylesheets: Vec::new(),
429 stylesheet_index: StylesheetSelectorIndex::default(),
430 cached_root_inherited_style: None,
431 gpu_2d_paths_enabled: strata_platform::gtk_gpu_2d_enabled(),
432 pointer_capture_target: None,
433 has_resize_listeners: false,
434 observed_element_sizes: std::collections::HashMap::new(),
435 last_pointer_pos: None,
436 pending_cursor_warp: None,
437 last_update_reconciled: false,
438 last_reconcile_stats: ReconcileStats::default(),
439 last_reconcile_bailout: None,
440 last_hover_fast_path_used: false,
441 last_hover_fast_path_bailout: None,
442 full_rebuilds_count: 1,
443 reconciled_updates_count: 0,
444 last_rebuild_reason: RebuildReason::InitialMount,
445 runtime_epoch: std::time::Instant::now(),
446 profile_history: FrameProfileHistory::default(),
447 prev_layout_cls_rects: Vec::new(),
448 active_dom_drag: None,
449 };
450
451 runtime.has_resize_listeners =
452 Self::blueprint_has_resize_listeners(&runtime.root_blueprint);
453 let initial_sheets = Self::collect_stylesheets_from_blueprint(&runtime.root_blueprint);
454 for sheet in &initial_sheets {
455 runtime.register_keyframes_stylesheet(sheet);
456 }
457 runtime.stylesheet_index = StylesheetSelectorIndex::from_stylesheets(&initial_sheets);
458 runtime.cached_root_inherited_style = if !initial_sheets.is_empty() {
459 let ctx = runtime.interaction_context();
460 Some(Self::resolve_document_root_inherited_style(
461 &runtime.root_blueprint,
462 &initial_sheets,
463 &ctx,
464 ))
465 } else {
466 None
467 };
468 runtime.cached_stylesheets = initial_sheets;
469 runtime.sync_tree_animations(0.0);
470 runtime.apply_viewport_clamps();
471 runtime.apply_scroll_offsets();
472 runtime.dispatch_resize_observers();
473 runtime
474 .spatial_index
475 .rebuild(&runtime.root_blueprint, &runtime.layout_root);
476 runtime.update_accessibility_tree();
477 runtime.compile_display_list();
478 runtime
479 }
480
481 pub fn apply_window_config(&mut self, config: &WindowConfig) -> &mut Self {
484 self.hover_tooltip_delay = config.tooltip_delay;
485 self.hover_tooltip_style = config.tooltip_style;
486 if self.hover_tooltip_visible {
487 self.paint_dirty = true;
488 }
489 self
490 }
491
492 pub fn set_hover_tooltip_delay(&mut self, delay: std::time::Duration) -> &mut Self {
494 self.hover_tooltip_delay = delay;
495 self
496 }
497
498 pub fn set_hover_tooltip_delay_ms(&mut self, delay_ms: u64) -> &mut Self {
500 self.hover_tooltip_delay = std::time::Duration::from_millis(delay_ms);
501 self
502 }
503
504 pub fn hover_tooltip_delay(&self) -> std::time::Duration {
506 self.hover_tooltip_delay
507 }
508
509 pub fn set_hover_tooltip_style(
511 &mut self,
512 style: strata_platform::HoverTooltipStyle,
513 ) -> &mut Self {
514 self.hover_tooltip_style = style;
515 if self.hover_tooltip_visible {
516 self.paint_dirty = true;
517 }
518 self
519 }
520
521 pub fn hover_tooltip_style(&self) -> strata_platform::HoverTooltipStyle {
523 self.hover_tooltip_style
524 }
525
526 pub fn tick_frame(&mut self) -> &DisplayList {
528 self.frame_count += 1;
529 self.unapply_scroll_offsets();
530 let compute_start = std::time::Instant::now();
531 self.layout_root
532 .compute_layout(self.viewport_width, self.viewport_height);
533 Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
534 self.layout_computations += 1;
535 self.frame_profile.layout += compute_start.elapsed();
536 if perf_logging_enabled() {
537 perf_log_ms(
538 "compute_layout_tick",
539 compute_start,
540 format!(
541 "{} layout nodes",
542 perf_count_layout_nodes(&self.layout_root)
543 ),
544 );
545 }
546 self.apply_viewport_clamps();
547 self.apply_scroll_offsets();
548 self.sync_active_input_layout();
549 self.dispatch_resize_observers();
550 self.spatial_index
551 .rebuild(&self.root_blueprint, &self.layout_root);
552 self.update_accessibility_tree();
553 self.compile_display_list();
554 &self.display_list
555 }
556
557 pub fn interaction_context(&self) -> InteractionContext<'_> {
559 InteractionContext {
560 hovered_path: self.current_hover_path.as_deref(),
561 focused_path: self.current_focus_path.as_deref(),
562 is_mouse_down: self.is_mouse_down,
563 is_dark_mode: self.is_dark_mode,
564 }
565 }
566
567 pub fn set_dark_mode(&mut self, is_dark: bool) -> bool {
569 if self.is_dark_mode != is_dark {
570 self.is_dark_mode = is_dark;
571 self.rebuild_layout_tree();
572 true
573 } else {
574 false
575 }
576 }
577
578 pub fn set_focus_path(&mut self, path: Option<Vec<usize>>) -> bool {
580 if self.current_focus_path != path {
581 self.current_focus_path = path;
582 self.rebuild_layout_tree();
583 true
584 } else {
585 false
586 }
587 }
588
589 pub fn rebuild_spatial_index(&mut self) {
591 self.spatial_index
592 .rebuild(&self.root_blueprint, &self.layout_root);
593 }
594
595 pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<strata_primitives::EntityId> {
597 self.spatial_index.query_entity_at_point(px, py)
598 }
599
600 pub fn query_event_at_point(
602 &self,
603 px: f32,
604 py: f32,
605 event_type: strata_dom::EventType,
606 ) -> Option<(
607 strata_primitives::EntityId,
608 std::rc::Rc<dyn Fn(strata_dom::Event)>,
609 strata_layout::Rect,
610 )> {
611 self.spatial_index.query_event_at_point(px, py, event_type)
612 }
613
614 pub fn find_layout_by_entity(
616 &self,
617 entity_id: strata_primitives::EntityId,
618 ) -> Option<&LayoutNode> {
619 self.layout_root.find_by_entity_id(entity_id)
620 }
621
622 pub fn find_layout_mut_by_entity(
624 &mut self,
625 entity_id: strata_primitives::EntityId,
626 ) -> Option<&mut LayoutNode> {
627 self.layout_root.find_by_entity_id_mut(entity_id)
628 }
629
630 pub fn find_blueprint_by_entity(
632 &self,
633 entity_id: strata_primitives::EntityId,
634 ) -> Option<&NodeBlueprint> {
635 self.root_blueprint.find_by_entity_id(entity_id)
636 }
637
638 pub fn query_element_rect(&self, element_id: &str) -> Option<strata_layout::Rect> {
640 fn find_rec(node: &LayoutNode, target_id: &str) -> Option<strata_layout::Rect> {
641 if node.element_id.as_deref() == Some(target_id) {
642 return Some(node.geometry.border_box);
643 }
644 for child in &node.children {
645 if let Some(rect) = find_rec(child, target_id) {
646 return Some(rect);
647 }
648 }
649 None
650 }
651 find_rec(&self.layout_root, element_id)
652 }
653
654 pub fn warp_cursor(&mut self, x: f32, y: f32) {
657 self.last_pointer_pos = Some((x, y));
658 self.pending_cursor_warp = Some((x, y));
659 #[cfg(target_os = "linux")]
660 strata_platform::gtk_warp_cursor(x as f64, y as f64);
661 }
662
663 pub fn set_cursor_position(&mut self, x: f32, y: f32) {
665 self.warp_cursor(x, y);
666 }
667
668 pub fn update_element_flex(
671 &mut self,
672 element_id: &str,
673 flex_grow: f32,
674 flex_shrink: f32,
675 flex_basis: Option<strata_style::types::Dimension>,
676 ) -> bool {
677 fn update_rec(
678 node: &mut LayoutNode,
679 target_id: &str,
680 flex_grow: f32,
681 flex_shrink: f32,
682 flex_basis: Option<strata_style::types::Dimension>,
683 ) -> bool {
684 if node.element_id.as_deref() == Some(target_id) {
685 node.style.flex_grow = flex_grow;
686 node.style.flex_shrink = flex_shrink;
687 if let Some(basis) = flex_basis {
688 node.style.flex_basis = basis;
689 }
690 node.invalidate_self_caches();
691 return true;
692 }
693 let mut changed = false;
694 for child in &mut node.children {
695 if update_rec(child, target_id, flex_grow, flex_shrink, flex_basis) {
696 changed = true;
697 }
698 }
699 if changed {
700 node.invalidate_self_caches();
701 }
702 changed
703 }
704 update_rec(
705 &mut self.layout_root,
706 element_id,
707 flex_grow,
708 flex_shrink,
709 flex_basis,
710 )
711 }
712
713 pub fn update_split_ratios(&mut self, updates: &[(&str, f32)]) -> bool {
716 let mut any_changed = false;
717 for &(id, ratio) in updates {
718 if self.update_element_flex(id, ratio, 1.0, None) {
719 any_changed = true;
720 }
721 }
722 if any_changed {
723 self.relayout_in_place();
724 }
725 any_changed
726 }
727
728 pub fn relayout_in_place(&mut self) {
731 self.unapply_scroll_offsets();
732 let compute_start = std::time::Instant::now();
733 self.layout_root
734 .compute_layout(self.viewport_width, self.viewport_height);
735 self.layout_computations += 1;
736 self.frame_profile.layout += compute_start.elapsed();
737 self.apply_viewport_clamps();
738 self.apply_scroll_offsets();
739 self.dispatch_resize_observers();
740 self.spatial_index
741 .rebuild(&self.root_blueprint, &self.layout_root);
742 self.paint_dirty = true;
743 self.compile_display_list();
744 }
745
746 pub(crate) fn blueprint_has_resize_listeners(bp: &NodeBlueprint) -> bool {
748 match bp {
749 NodeBlueprint::Element {
750 attributes,
751 children,
752 ..
753 } => {
754 attributes.iter().any(|a| {
755 matches!(
756 a,
757 strata_dom::Attribute::EventListener {
758 event: strata_dom::EventType::Resize,
759 ..
760 }
761 )
762 }) || children.iter().any(Self::blueprint_has_resize_listeners)
763 }
764 NodeBlueprint::Fragment(children) => {
765 children.iter().any(Self::blueprint_has_resize_listeners)
766 }
767 _ => false,
768 }
769 }
770
771 pub fn dispatch_resize_observers(&mut self) -> bool {
774 if !self.has_resize_listeners {
775 return false;
776 }
777 let mut pending: Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)> =
778 Vec::new();
779 let mut active_ids = std::collections::HashSet::new();
780 let mut path = Vec::new();
781
782 #[allow(clippy::too_many_arguments)]
783 fn collect_rec(
784 bp: &NodeBlueprint,
785 layout: &LayoutNode,
786 path: &mut Vec<usize>,
787 path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
788 observed: &mut std::collections::HashMap<u64, (f32, f32)>,
789 active_ids: &mut std::collections::HashSet<u64>,
790 pending: &mut Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)>,
791 ) {
792 if let NodeBlueprint::Element {
793 attributes,
794 children,
795 ..
796 } = bp
797 {
798 let node_id = path_node_ids
799 .get(path)
800 .copied()
801 .unwrap_or_else(|| path_to_node_id(path));
802 let mut resize_handlers = Vec::new();
803 for attr in attributes {
804 if let strata_dom::Attribute::EventListener {
805 event: strata_dom::EventType::Resize,
806 handler,
807 } = attr
808 {
809 resize_handlers.push(handler.clone());
810 }
811 }
812 if !resize_handlers.is_empty() {
813 active_ids.insert(node_id);
814 let w = layout.geometry.border_box.width;
815 let h = layout.geometry.border_box.height;
816 let changed = match observed.get(&node_id) {
817 Some(&(pw, ph)) => (w - pw).abs() > 0.25 || (h - ph).abs() > 0.25,
818 None => true,
819 };
820 if changed {
821 observed.insert(node_id, (w, h));
822 for handler in resize_handlers {
823 pending.push((handler, layout.geometry.border_box));
824 }
825 }
826 }
827 for (idx, child_layout) in layout.children.iter().enumerate() {
828 if let Some(child_bp) = children.get(idx) {
829 path.push(idx);
830 collect_rec(
831 child_bp,
832 child_layout,
833 path,
834 path_node_ids,
835 observed,
836 active_ids,
837 pending,
838 );
839 path.pop();
840 }
841 }
842 }
843 }
844
845 collect_rec(
846 &self.root_blueprint,
847 &self.layout_root,
848 &mut path,
849 &self.path_node_ids,
850 &mut self.observed_element_sizes,
851 &mut active_ids,
852 &mut pending,
853 );
854 self.observed_element_sizes
855 .retain(|id, _| active_ids.contains(id));
856
857 if pending.is_empty() {
858 return false;
859 }
860 for (handler, rect) in pending {
861 let mut ev = strata_dom::Event::new(strata_dom::EventType::Resize);
862 ev.client_x = rect.x as f64;
863 ev.client_y = rect.y as f64;
864 ev.offset_x = rect.width as f64;
865 ev.offset_y = rect.height as f64;
866 ev.width = rect.width as f64;
867 ev.height = rect.height as f64;
868 handler(ev);
869 }
870 true
871 }
872
873 fn element_attr_value<'a>(
874 attrs: &'a [strata_dom::Attribute],
875 key_name: &str,
876 ) -> Option<&'a str> {
877 attrs.iter().find_map(|a| match a {
878 strata_dom::Attribute::Property { key, value } if key == key_name => {
879 Some(value.as_str())
880 }
881 _ => None,
882 })
883 }
884
885 fn attributes_visually_equal(a: &[strata_dom::Attribute], b: &[strata_dom::Attribute]) -> bool {
886 let mut iter_a = a.iter().filter(|attr| {
887 !matches!(
888 attr,
889 strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
890 )
891 });
892 let mut iter_b = b.iter().filter(|attr| {
893 !matches!(
894 attr,
895 strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
896 )
897 });
898 loop {
899 match (iter_a.next(), iter_b.next()) {
900 (None, None) => return true,
901 (Some(x), Some(y)) => match (x, y) {
902 (
903 strata_dom::Attribute::Property { key: k1, value: v1 },
904 strata_dom::Attribute::Property { key: k2, value: v2 },
905 ) if k1 == k2 && v1 == v2 => {}
906 (
907 strata_dom::Attribute::DirectStyle(d1),
908 strata_dom::Attribute::DirectStyle(d2),
909 ) if std::rc::Rc::ptr_eq(d1, d2) => {}
910 (
911 strata_dom::Attribute::ScenePayload(s1),
912 strata_dom::Attribute::ScenePayload(s2),
913 ) if std::sync::Arc::ptr_eq(s1, s2) => {}
914 _ => return false,
915 },
916 _ => return false,
917 }
918 }
919 }
920
921 fn inherited_style_equal(
922 a: &strata_style::ComputedStyle,
923 b: &strata_style::ComputedStyle,
924 ) -> bool {
925 a.color == b.color
926 && a.font_family == b.font_family
927 && a.font_size == b.font_size
928 && a.root_font_size == b.root_font_size
929 && a.font_weight == b.font_weight
930 && a.font_style == b.font_style
931 && a.text_align == b.text_align
932 && a.line_height == b.line_height
933 && a.letter_spacing == b.letter_spacing
934 && a.text_decoration == b.text_decoration
935 && a.text_transform == b.text_transform
936 && a.text_overflow == b.text_overflow
937 && a.white_space == b.white_space
938 && a.cursor == b.cursor
939 && a.user_select == b.user_select
940 && a.pointer_events == b.pointer_events
941 && a.visibility == b.visibility
942 && a.caret_color == b.caret_color
943 && a.border_collapse == b.border_collapse
944 && a.border_spacing == b.border_spacing
945 && a.caption_side == b.caption_side
946 && a.custom_properties == b.custom_properties
947 }
948
949 fn blueprint_visually_equal(a: &NodeBlueprint, b: &NodeBlueprint) -> bool {
950 match (a, b) {
951 (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => t1 == t2,
952 (NodeBlueprint::Empty, NodeBlueprint::Empty) => true,
953 (
954 NodeBlueprint::Element {
955 tag: t1,
956 classes: cls1,
957 attributes: a1,
958 children: c1,
959 },
960 NodeBlueprint::Element {
961 tag: t2,
962 classes: cls2,
963 attributes: a2,
964 children: c2,
965 },
966 ) => {
967 t1 == t2
968 && cls1 == cls2
969 && c1.len() == c2.len()
970 && Self::attributes_visually_equal(a1, a2)
971 && c1
972 .iter()
973 .zip(c2.iter())
974 .all(|(x, y)| Self::blueprint_visually_equal(x, y))
975 }
976 _ => false,
977 }
978 }
979
980 pub(crate) fn materialize_cascade_meta(
987 bp: &NodeBlueprint,
988 node_path: &[usize],
989 ctx: &crate::runtime::InteractionContext,
990 group_state: (bool, bool, bool),
991 ) -> Option<CascadeElementMeta> {
992 let NodeBlueprint::Element {
993 tag,
994 classes,
995 attributes,
996 ..
997 } = bp
998 else {
999 return None;
1000 };
1001 if Self::is_style_tag(tag) {
1002 return None;
1003 }
1004 let is_hovered = ctx.hovered_path.is_some_and(|h| h.starts_with(node_path));
1005 let is_focused = ctx.focused_path.is_some_and(|f| f.starts_with(node_path));
1006 let is_active = is_hovered && ctx.is_mouse_down;
1007 let is_disabled = attributes.iter().any(|attr| match attr {
1008 strata_dom::Attribute::Property { key, value } => {
1009 key.eq_ignore_ascii_case("disabled") && !value.eq_ignore_ascii_case("false")
1010 }
1011 _ => false,
1012 });
1013 let (class_vec, id_val, attr_vec) = Self::extract_element_selector_meta(classes, attributes);
1014 Some(CascadeElementMeta {
1015 tag: Self::tag_as_str(tag),
1016 classes: class_vec,
1017 id: id_val,
1018 attributes: attr_vec,
1019 pseudo_state: strata_style::selector::PseudoState {
1020 is_hovered,
1021 is_focused,
1022 is_active,
1023 is_disabled,
1024 is_dark: ctx.is_dark_mode,
1025 is_group_hovered: group_state.0,
1026 is_group_focused: group_state.1,
1027 is_group_active: group_state.2,
1028 },
1029 })
1030 }
1031
1032 pub(crate) fn materialize_ancestor_metas(
1033 ancestor_stack: &[(&NodeBlueprint, (bool, bool, bool))],
1034 path_buf: &[usize],
1035 ctx: &crate::runtime::InteractionContext,
1036 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1037 sheet_index: &StylesheetSelectorIndex,
1038 ) -> Vec<CascadeElementMeta> {
1039 if stylesheets.is_empty() || !sheet_index.has_descendant_combinator_rules {
1040 return Vec::new();
1041 }
1042 let mut out = Vec::with_capacity(ancestor_stack.len());
1043 for (depth_idx, &(anc_bp, anc_group)) in ancestor_stack.iter().enumerate() {
1044 let anc_path = &path_buf[..depth_idx.min(path_buf.len())];
1045 if let Some(meta) = Self::materialize_cascade_meta(anc_bp, anc_path, ctx, anc_group) {
1046 out.push(meta);
1047 }
1048 }
1049 out
1050 }
1051
1052 pub(crate) fn materialize_preceding_sibling_metas(
1053 siblings: &[NodeBlueprint],
1054 child_idx: usize,
1055 parent_path: &[usize],
1056 ctx: &crate::runtime::InteractionContext,
1057 group_state: (bool, bool, bool),
1058 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1059 sheet_index: &StylesheetSelectorIndex,
1060 ) -> Vec<CascadeElementMeta> {
1061 if stylesheets.is_empty()
1062 || !sheet_index.has_sibling_combinator_or_positional_rules
1063 || child_idx == 0
1064 {
1065 return Vec::new();
1066 }
1067 let mut sib_path = Vec::with_capacity(parent_path.len() + 1);
1068 sib_path.extend_from_slice(parent_path);
1069 sib_path.push(0);
1070 let mut out = Vec::with_capacity(child_idx);
1071 for (j, sib_bp) in siblings[..child_idx].iter().enumerate() {
1072 if let Some(last) = sib_path.last_mut() {
1073 *last = j;
1074 }
1075 if let Some(meta) = Self::materialize_cascade_meta(sib_bp, &sib_path, ctx, group_state) {
1076 out.push(meta);
1077 }
1078 }
1079 out
1080 }
1081
1082 #[allow(clippy::too_many_arguments)]
1091 fn reconcile_layout_subtree<'a>(
1092 old_bp: &NodeBlueprint,
1093 new_bp: &'a NodeBlueprint,
1094 layout_node: &mut LayoutNode,
1095 parent_style: Option<&strata_style::ComputedStyle>,
1096 parent_inherited_changed: bool,
1097 ancestor_selector_changed: bool,
1098 force_restyle_self: bool,
1099 path_buf: &mut Vec<usize>,
1100 ancestor_stack: &mut Vec<(&'a NodeBlueprint, (bool, bool, bool))>,
1101 sibling_bps: &[NodeBlueprint],
1102 sibling_idx: usize,
1103 is_last_element_child: bool,
1104 group_state: (bool, bool, bool),
1105 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1106 sheet_index: &StylesheetSelectorIndex,
1107 ctx: &crate::runtime::InteractionContext,
1108 stats: &mut ReconcileStats,
1109 ) -> Option<bool> {
1110 match (old_bp, new_bp) {
1111 (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => {
1112 if t1 == t2 && !parent_inherited_changed && !force_restyle_self {
1113 stats.reused_subtrees += 1;
1114 Some(false)
1115 } else {
1116 *layout_node = Self::build_text_leaf_layout_node(t2.clone(), parent_style);
1117 stats.rebuilt_nodes += 1;
1118 Some(true)
1119 }
1120 }
1121 (NodeBlueprint::Empty, NodeBlueprint::Empty) => {
1122 stats.reused_subtrees += 1;
1123 Some(false)
1124 }
1125 (
1126 NodeBlueprint::Element { tag: t1, .. },
1127 NodeBlueprint::Element { tag: t2, .. },
1128 ) if t1 == t2 && Self::is_style_tag(t1) => {
1129 if let Some(eid) = new_bp.entity_id() {
1130 layout_node.entity_id = eid;
1131 }
1132 stats.reused_subtrees += 1;
1133 Some(false)
1134 }
1135 (
1136 NodeBlueprint::Element { tag: t1, .. },
1137 NodeBlueprint::Element { tag: t2, .. },
1138 ) if t1 == t2
1139 && matches!(
1140 t1,
1141 strata_dom::Tag::Svg
1142 | strata_dom::Tag::Path
1143 | strata_dom::Tag::Input
1144 | strata_dom::Tag::Textarea
1145 | strata_dom::Tag::Img
1146 | strata_dom::Tag::Canvas
1147 | strata_dom::Tag::Custom("Canvas3D")
1148 ) =>
1149 {
1150 if !parent_inherited_changed
1151 && !ancestor_selector_changed
1152 && !force_restyle_self
1153 && Self::blueprint_visually_equal(old_bp, new_bp)
1154 {
1155 if let Some(eid) = new_bp.entity_id() {
1156 layout_node.entity_id = eid;
1157 }
1158 stats.reused_subtrees += 1;
1159 Some(false)
1160 } else {
1161 None
1162 }
1163 }
1164 (
1165 NodeBlueprint::Element {
1166 tag: t1,
1167 classes: cls1,
1168 attributes: a1,
1169 children: c1,
1170 },
1171 NodeBlueprint::Element {
1172 tag: t2,
1173 classes: cls2,
1174 attributes: a2,
1175 children: c2,
1176 },
1177 ) if t1 == t2
1178 && !layout_node.is_top_layer
1179 && layout_node.children.len() == c1.len()
1180 && Self::element_attr_value(a1, "key") == Self::element_attr_value(a2, "key")
1181 && Self::element_attr_value(a1, "id") == Self::element_attr_value(a2, "id") =>
1182 {
1183 let self_props_changed = cls1 != cls2 || !Self::attributes_visually_equal(a1, a2);
1184 let single_text_changed = c1.len() == 1
1185 && c2.len() == 1
1186 && matches!(
1187 (&c1[0], &c2[0]),
1188 (NodeBlueprint::Text(x), NodeBlueprint::Text(y)) if x != y
1189 );
1190
1191 let (self_rewritten, child_inherited_changed) = if self_props_changed
1192 || parent_inherited_changed
1193 || ancestor_selector_changed
1194 || force_restyle_self
1195 || single_text_changed
1196 {
1197 let shallow_bp = NodeBlueprint::Element {
1198 tag: *t2,
1199 classes: cls2.clone(),
1200 attributes: a2.clone(),
1201 children: Vec::new(),
1202 };
1203 let mut ancestors_meta = Self::materialize_ancestor_metas(
1204 ancestor_stack,
1205 path_buf,
1206 ctx,
1207 stylesheets,
1208 sheet_index,
1209 );
1210 let parent_path_len = path_buf.len().saturating_sub(1);
1211 let preceding_sibs = if !path_buf.is_empty() {
1212 Self::materialize_preceding_sibling_metas(
1213 sibling_bps,
1214 sibling_idx,
1215 &path_buf[..parent_path_len],
1216 ctx,
1217 group_state,
1218 stylesheets,
1219 sheet_index,
1220 )
1221 } else {
1222 Vec::new()
1223 };
1224 let mut updated = Self::build_layout_tree_full(
1225 &shallow_bp,
1226 parent_style,
1227 path_buf,
1228 ctx,
1229 stylesheets,
1230 &mut ancestors_meta,
1231 &preceding_sibs,
1232 is_last_element_child,
1233 group_state,
1234 );
1235 Self::apply_single_text_inline_intrinsic_sizing(&mut updated.style, c2);
1236 if let Some(eid) = new_bp.entity_id() {
1237 updated.entity_id = eid;
1238 }
1239 let inh_changed =
1240 !Self::inherited_style_equal(&layout_node.style, &updated.style);
1241 updated.children = std::mem::take(&mut layout_node.children);
1242 *layout_node = updated;
1243 stats.rebuilt_nodes += 1;
1244 (true, inh_changed)
1245 } else {
1246 if let Some(eid) = new_bp.entity_id() {
1247 layout_node.entity_id = eid;
1248 }
1249 (false, false)
1250 };
1251
1252 let child_group_state = if Self::classes_have_group_marker(cls2) {
1253 let self_hovered = ctx.hovered_path.is_some_and(|h| h.starts_with(path_buf));
1254 let self_focused = ctx.focused_path.is_some_and(|f| f.starts_with(path_buf));
1255 let self_active = self_hovered && ctx.is_mouse_down;
1256 (
1257 group_state.0 || self_hovered,
1258 group_state.1 || self_focused,
1259 group_state.2 || self_active,
1260 )
1261 } else {
1262 group_state
1263 };
1264 let old_group_marker = Self::classes_have_group_marker(cls1);
1265 let group_marker_changed = old_group_marker != Self::classes_have_group_marker(cls2);
1266 let next_ancestor_selector_changed = ancestor_selector_changed
1267 || group_marker_changed
1268 || (self_props_changed && sheet_index.has_descendant_combinator_rules);
1269
1270 let parent_style_for_children = layout_node.style.clone();
1271 let child_count_changed = c1.len() != c2.len();
1272 let mut children_changed = child_count_changed;
1273 let common = c1.len().min(c2.len());
1274 let last_elem_idx = if !stylesheets.is_empty()
1275 && sheet_index.has_sibling_combinator_or_positional_rules
1276 {
1277 c2.iter().rposition(|bp| {
1278 matches!(bp, NodeBlueprint::Element { tag, .. } if !Self::is_style_tag(tag))
1279 })
1280 } else {
1281 None
1282 };
1283
1284 ancestor_stack.push((new_bp, group_state));
1285 let mut preceding_sibling_mutated = false;
1286
1287 for i in 0..common {
1288 path_buf.push(i);
1289 let is_last_child = last_elem_idx.map_or(i + 1 == c2.len(), |l| l == i);
1290 let interaction_shifted = child_count_changed
1293 && (ctx.hovered_path.is_some_and(|h| h.starts_with(path_buf))
1294 || ctx.focused_path.is_some_and(|f| f.starts_with(path_buf)));
1295 let positional_affected = sheet_index.has_sibling_combinator_or_positional_rules
1296 && (preceding_sibling_mutated
1297 || (child_count_changed && (i + 1 == common || is_last_child)));
1298 let child_force_restyle = interaction_shifted || positional_affected;
1299
1300 match Self::reconcile_layout_subtree(
1301 &c1[i],
1302 &c2[i],
1303 &mut layout_node.children[i],
1304 Some(&parent_style_for_children),
1305 child_inherited_changed,
1306 next_ancestor_selector_changed,
1307 child_force_restyle,
1308 path_buf,
1309 ancestor_stack,
1310 c2,
1311 i,
1312 is_last_child,
1313 child_group_state,
1314 stylesheets,
1315 sheet_index,
1316 ctx,
1317 stats,
1318 ) {
1319 Some(false) => {}
1320 Some(true) => {
1321 children_changed = true;
1322 if sheet_index.has_sibling_combinator_or_positional_rules {
1323 preceding_sibling_mutated = true;
1324 }
1325 }
1326 None => {
1327 let mut ancestors_meta = Self::materialize_ancestor_metas(
1328 ancestor_stack,
1329 path_buf,
1330 ctx,
1331 stylesheets,
1332 sheet_index,
1333 );
1334 let parent_path_len = path_buf.len().saturating_sub(1);
1335 let preceding_sibs = Self::materialize_preceding_sibling_metas(
1336 c2,
1337 i,
1338 &path_buf[..parent_path_len],
1339 ctx,
1340 child_group_state,
1341 stylesheets,
1342 sheet_index,
1343 );
1344 layout_node.children[i] = Self::build_layout_tree_full(
1345 &c2[i],
1346 Some(&parent_style_for_children),
1347 path_buf,
1348 ctx,
1349 stylesheets,
1350 &mut ancestors_meta,
1351 &preceding_sibs,
1352 is_last_child,
1353 child_group_state,
1354 );
1355 stats.rebuilt_nodes += 1;
1356 children_changed = true;
1357 if sheet_index.has_sibling_combinator_or_positional_rules {
1358 preceding_sibling_mutated = true;
1359 }
1360 }
1361 }
1362 path_buf.pop();
1363 }
1364
1365 if c2.len() < c1.len() {
1366 layout_node.children.truncate(c2.len());
1367 } else if c2.len() > c1.len() {
1368 for (offset, nc) in c2[common..].iter().enumerate() {
1369 let idx = common + offset;
1370 path_buf.push(idx);
1371 let is_last_child = last_elem_idx.map_or(idx + 1 == c2.len(), |l| l == idx);
1372 let mut ancestors_meta = Self::materialize_ancestor_metas(
1373 ancestor_stack,
1374 path_buf,
1375 ctx,
1376 stylesheets,
1377 sheet_index,
1378 );
1379 let parent_path_len = path_buf.len().saturating_sub(1);
1380 let preceding_sibs = Self::materialize_preceding_sibling_metas(
1381 c2,
1382 idx,
1383 &path_buf[..parent_path_len],
1384 ctx,
1385 child_group_state,
1386 stylesheets,
1387 sheet_index,
1388 );
1389 layout_node.children.push(Self::build_layout_tree_full(
1390 nc,
1391 Some(&parent_style_for_children),
1392 path_buf,
1393 ctx,
1394 stylesheets,
1395 &mut ancestors_meta,
1396 &preceding_sibs,
1397 is_last_child,
1398 child_group_state,
1399 ));
1400 stats.rebuilt_nodes += 1;
1401 path_buf.pop();
1402 }
1403 }
1404 ancestor_stack.pop();
1405
1406 if self_rewritten || children_changed {
1407 layout_node.inline_items.clear();
1408 layout_node.line_boxes.clear();
1409 layout_node.invalidate_self_caches();
1410 Some(true)
1411 } else {
1412 stats.reused_subtrees += 1;
1413 Some(false)
1414 }
1415 }
1416 _ => None,
1417 }
1418 }
1419
1420 pub fn update_root<F: FnOnce() -> View>(&mut self, root: F) {
1424 let view_start = std::time::Instant::now();
1425 let new_view = strata_dom::with_root_component_scope(root);
1426 self.frame_profile.view_render += view_start.elapsed();
1427 self.update_view(new_view);
1428 }
1429
1430 pub fn update_view(&mut self, new_view: View) {
1433 self.unapply_scroll_offsets();
1434 self.applied_scroll_offsets.clear();
1435 self.applied_portal_offsets.clear();
1436 if self.had_active_animations || self.has_active_animations() {
1437 self.restore_base_styles_to_layout_tree();
1438 }
1439 let mut next_blueprint = new_view.root.flatten_fragments();
1440 next_blueprint.ensure_entity_ids();
1441 let old_blueprint = std::mem::replace(&mut self.root_blueprint, next_blueprint);
1442 self.has_resize_listeners = Self::blueprint_has_resize_listeners(&self.root_blueprint);
1443 self.ir_graph = Self::build_ir_graph(&self.root_blueprint);
1444 let sheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
1445 let sheets_unchanged = self.cached_stylesheets == sheets;
1446 if !sheets_unchanged {
1447 for sheet in &sheets {
1448 self.register_keyframes_stylesheet(sheet);
1449 }
1450 self.stylesheet_index = StylesheetSelectorIndex::from_stylesheets(&sheets);
1451 self.cached_stylesheets = sheets;
1452 }
1453 self.capture_previous_node_sizes();
1454 let build_start = std::time::Instant::now();
1455 let mut stats = ReconcileStats::default();
1456 let mut bailout_reason: Option<String> = None;
1457
1458 let hovered_owned = self.current_hover_path.clone();
1459 let focused_owned = self.current_focus_path.clone();
1460 let ctx = crate::runtime::InteractionContext {
1461 hovered_path: hovered_owned.as_deref(),
1462 focused_path: focused_owned.as_deref(),
1463 is_mouse_down: self.is_mouse_down,
1464 is_dark_mode: self.is_dark_mode,
1465 };
1466 let next_root_inherited = if !self.cached_stylesheets.is_empty() {
1467 Some(Self::resolve_document_root_inherited_style(
1468 &self.root_blueprint,
1469 &self.cached_stylesheets,
1470 &ctx,
1471 ))
1472 } else {
1473 None
1474 };
1475 let root_inherited_changed = match (&self.cached_root_inherited_style, &next_root_inherited)
1476 {
1477 (Some(a), Some(b)) => !Self::inherited_style_equal(a, b),
1478 (None, None) => false,
1479 _ => true,
1480 };
1481
1482 let reconciled = if sheets_unchanged {
1483 let mut path_buf = Vec::new();
1484 let mut ancestor_stack = Vec::new();
1485 let ok = Self::reconcile_layout_subtree(
1486 &old_blueprint,
1487 &self.root_blueprint,
1488 &mut self.layout_root,
1489 next_root_inherited.as_ref(),
1490 root_inherited_changed,
1491 false,
1492 false,
1493 &mut path_buf,
1494 &mut ancestor_stack,
1495 &[],
1496 0,
1497 true,
1498 (false, false, false),
1499 &self.cached_stylesheets,
1500 &self.stylesheet_index,
1501 &ctx,
1502 &mut stats,
1503 )
1504 .is_some();
1505 if !ok {
1506 bailout_reason = Some("RootStructuralMismatch".to_string());
1507 }
1508 ok
1509 } else {
1510 bailout_reason = Some("StylesheetsChanged".to_string());
1511 false
1512 };
1513 self.cached_root_inherited_style = next_root_inherited;
1514
1515 if !reconciled {
1516 let ctx = self.interaction_context();
1517 self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
1518 self.full_rebuilds_count += 1;
1519 if let Some(ref reason) = bailout_reason {
1520 self.last_rebuild_reason = RebuildReason::LayoutReconcileBailout(reason.clone());
1521 }
1522 } else {
1523 self.reconciled_updates_count += 1;
1524 }
1525 self.last_update_reconciled = reconciled;
1526 self.last_reconcile_stats = stats;
1527 self.last_reconcile_bailout = bailout_reason;
1528 self.frame_profile.reconcile += build_start.elapsed();
1529 if perf_logging_enabled() {
1530 perf_log_ms(
1531 "build_layout_tree_update",
1532 build_start,
1533 format!(
1534 "{} blueprint nodes -> {} layout nodes (reconciled={}, reused={}, rebuilt={})",
1535 perf_count_blueprint_nodes(&self.root_blueprint),
1536 perf_count_layout_nodes(&self.layout_root),
1537 reconciled,
1538 stats.reused_subtrees,
1539 stats.rebuilt_nodes
1540 ),
1541 );
1542 }
1543 self.sync_active_input_layout();
1544 self.dynamic_text_bindings.clear();
1545 let mut path_buf = Vec::new();
1546 Self::collect_dynamic_text_bindings(
1547 &self.root_blueprint,
1548 &mut path_buf,
1549 &mut self.dynamic_text_bindings,
1550 );
1551 let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
1552 let sync_start = std::time::Instant::now();
1553 self.sync_tree_animations(now_ms);
1554 if self.had_active_animations || self.has_active_animations() {
1555 strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
1556 }
1557 if perf_logging_enabled() {
1558 perf_log_ms("sync_tree_animations", sync_start, "update_view");
1559 }
1560 self.refresh_hover_tooltip_after_view_update();
1561 self.tick_frame();
1562 }
1563
1564 pub fn sync_dynamic_text(&mut self) -> bool {
1568 if self.dynamic_text_bindings.is_empty() {
1569 return false;
1570 }
1571
1572 let mut changed = false;
1573 for binding in &mut self.dynamic_text_bindings {
1574 let new_text = (binding.closure)();
1575 if new_text != binding.last_value {
1576 binding.last_value = new_text.clone();
1577 let mut node_updated = false;
1578 if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &binding.path)
1579 {
1580 let is_mono = strata_layout::is_monospace_family(node.style.font_family);
1581 let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
1582 &new_text,
1583 node.style.font_size,
1584 node.style.line_height,
1585 None,
1586 is_mono,
1587 node.style.font_family,
1588 node.style.font_weight,
1589 node.style.font_style,
1590 );
1591 node.style.width = strata_style::types::Dimension::Px(w);
1592 node.style.height = strata_style::types::Dimension::Px(h);
1593 node.geometry.content_box.width = w;
1594 node.geometry.content_box.height = h;
1595 node.text = Some(new_text);
1596 node_updated = true;
1597 changed = true;
1598 }
1599 if node_updated {
1600 self.layout_root.invalidate_ancestors(&binding.path);
1601 }
1602 }
1603 }
1604
1605 if changed {
1606 self.tick_frame();
1607 true
1608 } else {
1609 false
1610 }
1611 }
1612
1613 pub fn cursor_theme(&self) -> &strata_platform::CursorTheme {
1616 self.cursor_theme
1617 .get_or_init(strata_platform::CursorTheme::load_active)
1618 }
1619
1620 pub fn mark_viewport_3d_dirty(&mut self) {
1622 self.viewport_3d_dirty = true;
1623 }
1624
1625 pub fn poll_retained_3d_dirty(&self) -> bool {
1628 if self.viewport_3d_dirty {
1629 return true;
1630 }
1631 self.tracked_retained_3d
1632 .iter()
1633 .any(|(handle, last_gens)| handle.generations() != *last_gens)
1634 }
1635
1636 pub fn acknowledge_retained_3d_presented(&mut self) {
1638 self.viewport_3d_dirty = false;
1639 for (handle, last_gens) in &mut self.tracked_retained_3d {
1640 *last_gens = handle.generations();
1641 }
1642 }
1643
1644 pub fn has_uncapped_canvas3d(&self) -> bool {
1646 fn walk(node: &NodeBlueprint) -> bool {
1647 if let NodeBlueprint::Element {
1648 attributes,
1649 children,
1650 ..
1651 } = node
1652 {
1653 if attributes.iter().any(|a| {
1654 matches!(
1655 a,
1656 strata_dom::Attribute::Property { key, value }
1657 if key == "data-strata-uncapped" && value == "true"
1658 )
1659 }) {
1660 return true;
1661 }
1662 if children.iter().any(walk) {
1663 return true;
1664 }
1665 }
1666 false
1667 }
1668 walk(&self.root_blueprint)
1669 }
1670
1671 pub fn mark_paint_dirty(&mut self) {
1673 self.paint_dirty = true;
1674 }
1675
1676 pub fn is_paint_dirty(&self) -> bool {
1678 self.paint_dirty
1679 }
1680
1681 pub fn compiles_skipped(&self) -> u64 {
1683 self.compiles_skipped
1684 }
1685
1686 pub fn compile_display_list_if_dirty(&mut self) -> bool {
1689 if !self.paint_dirty {
1690 self.compiles_skipped += 1;
1691 return false;
1692 }
1693 self.compile_display_list();
1694 true
1695 }
1696
1697 pub fn compile_display_list(&mut self) {
1699 let compile_start = std::time::Instant::now();
1700 let viewport = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
1701 Some(strata_layout::Rect::new(
1702 0.0,
1703 0.0,
1704 self.viewport_width,
1705 self.viewport_height,
1706 ))
1707 } else {
1708 None
1709 };
1710 let scrollbar_overlays = self.build_scrollbar_overlays();
1711 self.display_list =
1712 strata_render::compositor::Compositor::build_document_display_list_with_scrollbars(
1713 &self.layout_root,
1714 viewport,
1715 &scrollbar_overlays,
1716 );
1717 strata_render::compositor::Compositor::append_top_layer_portals_with_scrollbars(
1718 &self.layout_root,
1719 &mut self.display_list,
1720 viewport,
1721 &scrollbar_overlays,
1722 );
1723 self.tracked_retained_3d.clear();
1724 for cmd in &self.display_list.commands {
1725 if let strata_render::compositor::DrawCommand::DrawViewport3D { scene, .. } = cmd {
1726 if let Some(handle) = scene.retained_handle() {
1727 self.tracked_retained_3d
1728 .push((handle.clone(), handle.generations()));
1729 }
1730 }
1731 }
1732 self.render_active_input_caret();
1733 self.render_hover_tooltip();
1734 if self.gpu_2d_paths_enabled {
1735 self.gpu_path_pipeline
1736 .resize(self.viewport_width, self.viewport_height);
1737 self.gpu_path_pipeline
1738 .compile_frame(&self.display_list, None);
1739 }
1740 self.frame_profile.compile += compile_start.elapsed();
1741 self.paint_dirty = false;
1742
1743 static COMPILE_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1744 let frame = COMPILE_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1745 if frame < 6 || frame.is_multiple_of(120) {
1746 perf_log_ms(
1747 "compile_display_list",
1748 compile_start,
1749 format!(
1750 "frame {} {}x{} {} commands (gpu_2d_paths={})",
1751 frame,
1752 self.viewport_width,
1753 self.viewport_height,
1754 self.display_list.commands.len(),
1755 self.gpu_2d_paths_enabled
1756 ),
1757 );
1758 }
1759 }
1760
1761 pub fn set_gpu_2d_paths_enabled(&mut self, enabled: bool) {
1765 self.gpu_2d_paths_enabled = enabled;
1766 }
1767
1768 pub fn gpu_2d_paths_enabled(&self) -> bool {
1770 self.gpu_2d_paths_enabled
1771 }
1772
1773 pub fn compile_gpu_paths_now(&mut self) -> usize {
1775 self.gpu_path_pipeline
1776 .resize(self.viewport_width, self.viewport_height);
1777 self.gpu_path_pipeline
1778 .compile_frame(&self.display_list, None)
1779 }
1780
1781 #[inline]
1783 pub fn gpu_path_segments(&self) -> &[strata_render::gpu_path::GpuPathSegment] {
1784 &self.gpu_path_pipeline.batch.segments
1785 }
1786
1787 #[inline]
1789 pub fn gpu_path_uniform_bytes(&self) -> &[u8] {
1790 self.gpu_path_pipeline.uniform_bytes()
1791 }
1792
1793 pub fn step_event(&mut self, event: &PlatformEvent) -> bool {
1796 let input_start = std::time::Instant::now();
1797 #[cfg(feature = "devtools")]
1798 if let Some(ref mut dt) = self.devtools {
1799 if strata_devtools::DevToolsEventInterceptor::intercept(&mut dt.hud, event) {
1800 self.frame_profile.input_dispatch += input_start.elapsed();
1801 return true;
1802 }
1803 }
1804
1805 let mut needs_redraw = match event {
1806 PlatformEvent::WindowResized { width, height } => {
1807 self.viewport_width = *width as f32;
1808 self.viewport_height = *height as f32;
1809 #[cfg(feature = "devtools")]
1810 if let Some(ref mut dt) = self.devtools {
1811 dt.hud
1812 .update_bounds(self.viewport_width, self.viewport_height);
1813 }
1814 self.tick_frame();
1815 true
1816 }
1817 PlatformEvent::ScaleFactorChanged { scale_factor } => {
1818 self.dpr = *scale_factor;
1819 self.tick_frame();
1820 true
1821 }
1822 PlatformEvent::WindowFocused(_) => false,
1823 PlatformEvent::WindowCloseRequested => false,
1824 PlatformEvent::Scroll {
1825 delta_x, delta_y, ..
1826 } => {
1827 let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1828 let (wheel_handled, scroll_changed) = self.dispatch_smooth_scroll_action(
1829 self.last_mouse_pos.0,
1830 self.last_mouse_pos.1,
1831 *delta_x,
1832 *delta_y,
1833 );
1834 if wheel_handled {
1835 self.rebuild_layout_tree();
1836 true
1837 } else {
1838 scroll_changed || tooltip_dismissed
1839 }
1840 }
1841 PlatformEvent::AnimationTick => {
1842 let scroll_changed = self.poll_smooth_scroll();
1843 let anim_changed = self.poll_animations();
1844 let caret_changed = self.poll_caret_blink();
1845 let tooltip_changed = self.poll_hover_tooltip();
1846 scroll_changed || anim_changed || caret_changed || tooltip_changed
1847 }
1848 PlatformEvent::MouseMove { x, y } => {
1849 self.last_mouse_pos = (*x, *y);
1850 let cur = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, *x, *y);
1851 self.current_cursor = cur;
1852 let hover_changed = self.update_hover(*x, *y);
1853 self.dispatch_pointer_move_action(*x, *y).needs_redraw() || hover_changed
1854 }
1855 PlatformEvent::MouseDown { button, x, y } => {
1856 let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1857 let btn_idx = button.to_button_index();
1858 if *button == strata_platform::MouseButton::Left {
1859 self.is_mouse_down = true;
1860 }
1861 let action = self.dispatch_pointer_down_action_with_button_and_modifiers(
1862 *x,
1863 *y,
1864 btn_idx,
1865 Default::default(),
1866 );
1867 let click_invoked = if *button != strata_platform::MouseButton::Right {
1868 self.dispatch_mouse_click(*x, *y, btn_idx, 1)
1869 } else {
1870 self.dispatch_context_menu(*x, *y)
1871 };
1872 let dynamic_updated = self.sync_dynamic_text();
1873 if action.needs_rebuild() || click_invoked || dynamic_updated {
1874 self.rebuild_layout_tree();
1875 true
1876 } else {
1877 tooltip_dismissed || action.needs_redraw() || self.restyle_for_active_change()
1878 }
1879 }
1880 PlatformEvent::MouseUp { button, x, y } => {
1881 let btn_idx = button.to_button_index();
1882 let was_mouse_down = self.is_mouse_down;
1883 if *button == strata_platform::MouseButton::Left {
1884 self.is_mouse_down = false;
1885 }
1886 let action = self.dispatch_pointer_up_action_with_button(*x, *y, btn_idx);
1887 if action.needs_rebuild() {
1888 self.rebuild_layout_tree();
1889 true
1890 } else if was_mouse_down {
1891 action.needs_redraw() || self.restyle_for_active_change()
1892 } else {
1893 action.needs_redraw()
1894 }
1895 }
1896 PlatformEvent::CursorLeft => {
1897 self.is_mouse_down = false;
1898 self.current_cursor = strata_platform::window::CursorIcon::Default;
1899 self.clear_hover()
1900 }
1901 PlatformEvent::KeyDown { .. }
1902 | PlatformEvent::KeyUp { .. }
1903 | PlatformEvent::ReceivedCharacter(_)
1904 | PlatformEvent::ImePreedit { .. }
1905 | PlatformEvent::ImeCommit(_) => {
1906 let tooltip_dismissed = matches!(event, PlatformEvent::KeyDown { .. })
1907 && self.dismiss_hover_tooltip_and_repaint();
1908 let res = self.dispatch_key_event(event);
1909 let dynamic_updated = self.sync_dynamic_text();
1910 tooltip_dismissed || res.needs_redraw() || dynamic_updated
1911 }
1912 PlatformEvent::FileDrop(paths) => {
1913 let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1914 let drop_handled = self.dispatch_file_drop(paths.clone());
1915 let dynamic_updated = self.sync_dynamic_text();
1916 if drop_handled || dynamic_updated {
1917 self.rebuild_layout_tree();
1918 true
1919 } else {
1920 tooltip_dismissed
1921 }
1922 }
1923 _ => false,
1924 };
1925
1926 if self.poll_dom_mutations(None) {
1927 needs_redraw = true;
1928 }
1929
1930 if needs_redraw {
1931 self.paint_dirty = true;
1932 }
1933 self.frame_profile.input_dispatch += input_start.elapsed();
1934 needs_redraw
1935 }
1936
1937 pub fn layout_computations(&self) -> u64 {
1939 self.layout_computations
1940 }
1941
1942 pub fn last_update_reconciled(&self) -> bool {
1944 self.last_update_reconciled
1945 }
1946
1947 pub fn last_reconcile_stats(&self) -> ReconcileStats {
1949 self.last_reconcile_stats
1950 }
1951
1952 pub fn last_reconcile_bailout(&self) -> Option<&str> {
1954 self.last_reconcile_bailout.as_deref()
1955 }
1956
1957 pub fn last_hover_fast_path_used(&self) -> bool {
1959 self.last_hover_fast_path_used
1960 }
1961
1962 pub fn last_hover_fast_path_bailout(&self) -> Option<&str> {
1964 self.last_hover_fast_path_bailout.as_deref()
1965 }
1966
1967 pub fn full_rebuilds_count(&self) -> u64 {
1969 self.full_rebuilds_count
1970 }
1971
1972 pub fn reconciled_updates_count(&self) -> u64 {
1974 self.reconciled_updates_count
1975 }
1976
1977 pub fn last_rebuild_reason(&self) -> &RebuildReason {
1979 &self.last_rebuild_reason
1980 }
1981
1982 pub fn set_rebuild_reason(&mut self, reason: RebuildReason) {
1984 self.last_rebuild_reason = reason;
1985 }
1986
1987 pub fn frame_profile(&self) -> FrameProfile {
1989 self.frame_profile
1990 }
1991
1992 pub fn last_frame_profile(&self) -> Option<&FrameProfileRecord> {
1994 self.profile_history.last()
1995 }
1996
1997 pub fn perf_profile_summary(&self) -> PerfProfileSummary {
1999 self.profile_history.summary(
2000 self.frame_count,
2001 self.full_rebuilds_count,
2002 self.reconciled_updates_count,
2003 )
2004 }
2005
2006 pub fn set_frame_profile_hook(&mut self, hook: Option<Box<dyn FnMut(&FrameProfile)>>) {
2008 self.frame_profile_hook = hook.map(FrameProfileHook);
2009 }
2010
2011 pub fn record_input_dispatch_time(&mut self, elapsed: std::time::Duration) {
2013 self.frame_profile.input_dispatch += elapsed;
2014 }
2015
2016 pub fn record_signal_drain_time(&mut self, elapsed: std::time::Duration) {
2018 self.frame_profile.signal_drain += elapsed;
2019 }
2020
2021 pub fn record_view_render_time(&mut self, elapsed: std::time::Duration) {
2023 self.frame_profile.view_render += elapsed;
2024 }
2025
2026 pub fn record_raster_time(&mut self, elapsed: std::time::Duration) {
2028 self.frame_profile.raster += elapsed;
2029 }
2030
2031 pub fn record_wgpu_3d_submit_time(&mut self, elapsed: std::time::Duration) {
2033 self.frame_profile.wgpu_3d_submit += elapsed;
2034 }
2035
2036 pub fn record_present_time(&mut self, elapsed: std::time::Duration) {
2038 self.frame_profile.present += elapsed;
2039 }
2040
2041 fn compute_real_layout_shift_score(&mut self) -> f32 {
2044 let mut cur_rects: Vec<(f32, f32, f32, f32)> = Vec::new();
2045 for child in self.layout_root.children.iter().take(32) {
2046 let b = child.geometry.border_box;
2047 cur_rects.push((b.x, b.y, b.width, b.height));
2048 }
2049 let mut max_shift = 0.0f32;
2050 let vw = self.viewport_width.max(1.0);
2051 let vh = self.viewport_height.max(1.0);
2052 let max_dim = vw.max(vh);
2053 let vp_area = (vw * vh).max(1.0);
2054 for (prev, cur) in self.prev_layout_cls_rects.iter().zip(cur_rects.iter()) {
2055 let dx = (cur.0 - prev.0).abs();
2056 let dy = (cur.1 - prev.1).abs();
2057 if dx > 0.5 || dy > 0.5 {
2058 let dist = (dx.max(dy) / max_dim).clamp(0.0, 1.0);
2059 let impact = ((prev.2 * prev.3).max(cur.2 * cur.3) / vp_area).clamp(0.0, 1.0);
2060 max_shift = max_shift.max(impact * dist);
2061 }
2062 }
2063 self.prev_layout_cls_rects = cur_rects;
2064 max_shift
2065 }
2066
2067 pub fn finish_frame_profile(&mut self) -> FrameProfile {
2070 let done = std::mem::take(&mut self.frame_profile);
2071 if let Some(hook) = self.frame_profile_hook.as_mut() {
2072 (hook.0)(&done);
2073 }
2074 done
2075 }
2076
2077 pub fn finalize_frame_telemetry(&mut self, outcome: &'static str) -> FrameProfileRecord {
2081 let gpu_tel = strata_platform::gtk_last_gpu_telemetry();
2082 let (tiles_dirty, tiles_total) = strata_platform::gtk_last_tile_cache_stats();
2083 let tile_cache_hit_pct = if tiles_total > 0 {
2084 ((tiles_total.saturating_sub(tiles_dirty)) as f32 / tiles_total as f32) * 100.0
2085 } else {
2086 100.0
2087 };
2088 let s3d_total = gpu_tel.scene3d_cache_hits + gpu_tel.scene3d_cache_misses;
2089 let scene3d_cache_hit_pct = if s3d_total > 0 {
2090 (gpu_tel.scene3d_cache_hits as f32 / s3d_total as f32) * 100.0
2091 } else {
2092 100.0
2093 };
2094 let (text_hits, text_misses) = strata_layout::text_measure_cache_stats();
2095 let text_total = text_hits + text_misses;
2096 let glyph_atlas_hit_pct = if text_total > 0 {
2097 (text_hits as f32 / text_total as f32) * 100.0
2098 } else {
2099 100.0
2100 };
2101
2102 self.frame_profile.gpu_3d_us = gpu_tel
2103 .gpu_shadow_pass_us
2104 .saturating_add(gpu_tel.gpu_3d_pass_us);
2105 self.frame_profile.gpu_2d_overlay_us = gpu_tel.gpu_2d_overlay_pass_us;
2106 self.frame_profile.gpu_timestamps_valid = gpu_tel.gpu_timestamps_supported;
2107
2108 let done = self.finish_frame_profile();
2109 let cls_score = self.compute_real_layout_shift_score();
2110 let timestamp_us = self.runtime_epoch.elapsed().as_micros() as u64;
2111 let (heap_alloc_count, heap_alloc_bytes) = profile::take_frame_heap_alloc_delta();
2112
2113 let dom_nodes = perf_count_blueprint_nodes(&self.root_blueprint);
2114 let layout_nodes = perf_count_layout_nodes(&self.layout_root);
2115 let display_cmds = self.display_list.len();
2116
2117 let reconcile_us = if !done.reconcile.is_zero() {
2118 done.reconcile.as_micros() as u32
2119 } else {
2120 done.rebuild.as_micros() as u32
2121 };
2122 let style_cascade_us = done.style_cascade.as_micros() as u32;
2123 let input_dispatch_us = done.input_dispatch.as_micros() as u32;
2124 let signal_drain_us = done.signal_drain.as_micros() as u32;
2125 let view_render_us = done.view_render.as_micros() as u32;
2126 let layout_us = done.layout.as_micros() as u32;
2127 let display_list_build_us = done.compile.as_micros() as u32;
2128 let raster_us = done.raster.as_micros() as u32;
2129 let wgpu_3d_submit_us = done.wgpu_3d_submit.as_micros() as u32;
2130 let present_us = done.present.as_micros() as u32;
2131 let total_cpu_us = done.total().as_micros() as u32;
2132
2133 let reason_str = self.last_rebuild_reason.to_string();
2134 let record = FrameProfileRecord {
2135 frame_index: self.frame_count,
2136 timestamp_us,
2137 rebuild_reason: reason_str.clone(),
2138 outcome: outcome.to_string(),
2139 input_dispatch_us,
2140 signal_drain_us,
2141 view_render_us,
2142 reconcile_us,
2143 style_cascade_us,
2144 layout_us,
2145 display_list_build_us,
2146 raster_us,
2147 wgpu_3d_submit_us,
2148 present_us,
2149 total_cpu_us,
2150 gpu_3d_us: done.gpu_3d_us,
2151 gpu_2d_overlay_us: done.gpu_2d_overlay_us,
2152 gpu_timestamps_valid: done.gpu_timestamps_valid,
2153 dom_nodes: dom_nodes as u32,
2154 layout_nodes: layout_nodes as u32,
2155 display_cmds: display_cmds as u32,
2156 tiles_dirty,
2157 tiles_total,
2158 tile_cache_hit_pct,
2159 reconciled_subtrees: self.last_reconcile_stats.reused_subtrees as u32,
2160 rebuilt_nodes: self.last_reconcile_stats.rebuilt_nodes as u32,
2161 full_rebuilds: self.full_rebuilds_count,
2162 reconciled: self.last_update_reconciled,
2163 hover_fast_path_used: self.last_hover_fast_path_used,
2164 hover_fast_path_bailout: self.last_hover_fast_path_bailout.clone(),
2165 reconcile_bailout: self.last_reconcile_bailout.clone(),
2166 scene3d_cache_hits: gpu_tel.scene3d_cache_hits,
2167 scene3d_cache_misses: gpu_tel.scene3d_cache_misses,
2168 scene3d_cache_hit_pct,
2169 glyph_atlas_hit_pct,
2170 gpu_memory_bytes: gpu_tel.gpu_memory_bytes,
2171 heap_alloc_count,
2172 heap_alloc_bytes,
2173 layout_shift_score: cls_score,
2174 };
2175 self.profile_history.push(record.clone());
2176
2177 #[cfg(feature = "devtools")]
2178 if let Some(ref mut dt) = self.devtools {
2179 let ui_tid = strata_devtools::current_thread_id_u64();
2180 let gpu_tid = ui_tid.wrapping_add(1).max(2);
2181 let gpu_total_hw = gpu_tel
2182 .gpu_shadow_pass_us
2183 .saturating_add(gpu_tel.gpu_3d_pass_us)
2184 .saturating_add(gpu_tel.gpu_2d_overlay_pass_us);
2185 let sample = strata_devtools::FrameTimingSample {
2186 frame_index: self.frame_count,
2187 timestamp_us,
2188 pid: std::process::id(),
2189 ui_thread_id: ui_tid,
2190 worker_thread_id: 0,
2191 gpu_thread_id: gpu_tid,
2192 vsync_wait_us: 0,
2193 input_dispatch_us,
2194 signal_drain_us,
2195 view_render_us,
2196 parallel_reconcile_us: reconcile_us,
2197 style_cascade_us,
2198 layout_solve_us: layout_us,
2199 display_list_build_us,
2200 raster_2d_us: raster_us,
2201 gpu_submit_us: wgpu_3d_submit_us,
2202 present_us,
2203 gpu_raster_duration_us: if gpu_tel.gpu_timestamps_supported {
2204 gpu_total_hw
2205 } else {
2206 raster_us.saturating_add(wgpu_3d_submit_us)
2207 },
2208 gpu_shadow_pass_us: gpu_tel.gpu_shadow_pass_us,
2209 gpu_3d_pass_us: gpu_tel.gpu_3d_pass_us,
2210 gpu_2d_overlay_pass_us: gpu_tel.gpu_2d_overlay_pass_us,
2211 gpu_timestamps_valid: gpu_tel.gpu_timestamps_supported,
2212 total_cpu_frame_us: total_cpu_us,
2213 frame_budget_us: dt.profiler.frame_budget_us(),
2214 layout_shift_score: cls_score,
2215 };
2216 dt.profiler.record_sample(sample);
2217
2218 let react_snap = strata_dom::reactive_telemetry_snapshot();
2219 let arena_est_bytes = dom_nodes
2220 .saturating_mul(std::mem::size_of::<NodeBlueprint>())
2221 .saturating_add(layout_nodes.saturating_mul(std::mem::size_of::<strata_layout::LayoutNode>()))
2222 .saturating_add(display_cmds.saturating_mul(std::mem::size_of::<strata_render::DrawCommand>()));
2223 let arena_cap_bytes = (arena_est_bytes.max(64 * 1024)).next_power_of_two();
2224 dt.arena_inspector
2225 .record_sample(strata_devtools::ArenaTelemetrySample::new(
2226 0,
2227 arena_est_bytes,
2228 arena_cap_bytes,
2229 arena_est_bytes,
2230 self.frame_count,
2231 ));
2232 if heap_alloc_bytes > 0 {
2233 dt.heap_tracker.record_allocation(heap_alloc_bytes as usize);
2234 }
2235 dt.live_telemetry = strata_devtools::HudLiveTelemetry {
2236 reactive_active_signals: react_snap.active_signals,
2237 reactive_active_subscribers: react_snap.active_subscribers,
2238 reactive_total_reads: react_snap.total_reads,
2239 reactive_total_writes: react_snap.total_writes,
2240 reactive_total_flushes: react_snap.total_flushes,
2241 reactive_cycle_guard_trips: react_snap.cycle_guard_trips,
2242 last_rebuild_reason: reason_str.clone(),
2243 dirty_signal_names: react_snap.dirty_signal_names,
2244 top_signals: react_snap
2245 .signals
2246 .iter()
2247 .take(8)
2248 .map(|s| (s.name.clone(), s.write_count, s.read_count, s.subscriber_count))
2249 .collect(),
2250 dom_node_count: dom_nodes,
2251 layout_node_count: layout_nodes,
2252 display_cmd_count: display_cmds,
2253 arena_allocated_bytes: arena_est_bytes,
2254 arena_capacity_bytes: arena_cap_bytes,
2255 heap_alloc_bytes,
2256 heap_alloc_count,
2257 gpu_memory_bytes: gpu_tel.gpu_memory_bytes,
2258 tiles_dirty,
2259 tiles_total,
2260 tile_cache_hit_pct,
2261 scene3d_cache_hit_pct,
2262 glyph_cache_hit_pct: glyph_atlas_hit_pct,
2263 reconciled_updates: self.reconciled_updates_count,
2264 full_rebuilds: self.full_rebuilds_count,
2265 };
2266
2267 if outcome == "Dirty" || dt.time_travel.is_empty() {
2268 let mut ir_hash: u64 = 0xcbf2_9ce4_8422_2325;
2269 ir_hash ^= (dom_nodes as u64).wrapping_mul(0x100_0000_01b3);
2270 ir_hash ^= (layout_nodes as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
2271 ir_hash ^= (display_cmds as u64).wrapping_mul(0x517c_c1b7_2722_0a95);
2272 ir_hash ^= self.layout_computations;
2273 let sig_values: Vec<(usize, String)> = react_snap
2274 .signals
2275 .iter()
2276 .take(16)
2277 .map(|s| {
2278 (
2279 s.signal_id,
2280 format!("{}:w{}r{}", s.name, s.write_count, s.read_count),
2281 )
2282 })
2283 .collect();
2284 dt.time_travel
2285 .record_snapshot(timestamp_us, reason_str, sig_values, ir_hash);
2286 }
2287 dt.cdp_dispatcher.update_from_ir(
2288 &self.ir_graph,
2289 &self.base_node_styles,
2290 self.frame_count,
2291 self.layout_computations,
2292 );
2293 }
2294
2295 record
2296 }
2297
2298 pub fn render_frame<P: SurfacePresenter>(
2300 &mut self,
2301 compositor: &mut SwapchainCompositor,
2302 presenter: &mut P,
2303 force_redraw: bool,
2304 ) -> Result<bool, PresentError> {
2305 let retained_3d_dirty = self.poll_retained_3d_dirty();
2306 let did_dirty_tick = self.paint_dirty || self.frame_count == 0 || force_redraw;
2307 if did_dirty_tick {
2308 self.tick_frame();
2309 } else {
2310 self.compiles_skipped += 1;
2311 if retained_3d_dirty {
2312 self.frame_count += 1;
2313 }
2314 }
2315
2316 #[cfg(feature = "devtools")]
2317 if let Some(ref mut dt) = self.devtools {
2318 if dt.hud.state.is_visible {
2319 dt.render_hud_overlay(&mut self.display_list);
2320 }
2321 }
2322
2323 let present_start = std::time::Instant::now();
2324 let res = compositor.render_and_present(
2325 &self.display_list,
2326 presenter,
2327 force_redraw || retained_3d_dirty,
2328 );
2329 self.acknowledge_retained_3d_presented();
2330 self.frame_profile.present += present_start.elapsed();
2331
2332 let outcome = if did_dirty_tick {
2333 "Dirty"
2334 } else if retained_3d_dirty {
2335 "RepaintCanvas3D"
2336 } else {
2337 "Clean"
2338 };
2339 self.finalize_frame_telemetry(outcome);
2340
2341 res
2342 }
2343
2344 #[cfg(feature = "devtools")]
2345 pub fn enable_devtools(&mut self) -> &mut strata_devtools::DevTools {
2347 if self.devtools.is_none() {
2348 let mut dt = strata_devtools::DevTools::new();
2349 dt.hud
2350 .update_bounds(self.viewport_width, self.viewport_height);
2351 self.devtools = Some(dt);
2352 }
2353 self.devtools.as_mut().unwrap()
2354 }
2355
2356 #[cfg(feature = "devtools")]
2357 pub fn devtools(&self) -> Option<&strata_devtools::DevTools> {
2359 self.devtools.as_ref()
2360 }
2361
2362 #[cfg(feature = "devtools")]
2363 pub fn devtools_mut(&mut self) -> Option<&mut strata_devtools::DevTools> {
2365 self.devtools.as_mut()
2366 }
2367
2368 pub fn run_with_window<W, E, P>(
2370 &mut self,
2371 window: &mut W,
2372 event_loop: &mut E,
2373 compositor: &mut SwapchainCompositor,
2374 presenter: &mut P,
2375 ) where
2376 W: PlatformWindow,
2377 E: EventLoop,
2378 P: SurfacePresenter,
2379 {
2380 let _ = self.render_frame(compositor, presenter, true);
2382
2383 event_loop.run(|event, control| {
2384 match event {
2385 PlatformEvent::WindowResized { width, height } => {
2386 compositor.resize(width, height, self.dpr);
2387 let _ = presenter.resize(width, height);
2388 }
2389 PlatformEvent::ScaleFactorChanged { scale_factor } => {
2390 compositor.resize(
2391 self.viewport_width as u32,
2392 self.viewport_height as u32,
2393 scale_factor,
2394 );
2395 }
2396 PlatformEvent::WindowCloseRequested => {
2397 *control = EventLoopControl::Exit;
2398 return;
2399 }
2400 _ => {}
2401 }
2402
2403 let needs_redraw = self.step_event(&event);
2404 window.set_cursor(self.current_cursor());
2405
2406 if needs_redraw || window.is_redraw_requested() {
2407 let _ = self.render_frame(compositor, presenter, false);
2408 }
2409
2410 *control = EventLoopControl::Wait;
2412 });
2413 }
2414
2415 pub fn render_to_framebuffer(&mut self) -> strata_render::rasterizer::FrameBuffer {
2417 self.tick_frame();
2418 let width = (self.viewport_width * self.dpr).max(1.0).ceil() as usize;
2419 let height = (self.viewport_height * self.dpr).max(1.0).ceil() as usize;
2420 let mut fb = strata_render::rasterizer::FrameBuffer::new(width, height);
2421 fb.execute_display_list(&self.display_list);
2422 fb
2423 }
2424
2425 pub fn export_png<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), String> {
2427 let fb = self.render_to_framebuffer();
2428 fb.export_png(path).map_err(|e| e.to_string())
2429 }
2430
2431 #[cfg(feature = "devtools")]
2432 pub fn sync_to_devtools(&self, dispatcher: &strata_devtools::cdp::CdpDispatcher) {
2434 dispatcher.update_from_ir(
2435 &self.ir_graph,
2436 &self.base_node_styles,
2437 self.frame_count,
2438 self.layout_computations,
2439 );
2440 }
2441}