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;
15pub mod launch;
16pub mod platforms;
17pub mod types;
18
19mod a11y;
20mod animation;
21mod canvas3d;
22pub mod dom_hydration;
23mod events;
24mod hit_test;
25mod hover;
26mod image;
27mod input_hit_test;
28mod layout_tree;
29mod mcp;
30mod profile;
31mod scroll;
32mod scrollbar;
33mod selection;
34pub mod spatial;
35mod tailwind;
36pub mod test_support;
37
38pub use app::*;
39pub use dom_hydration::*;
40pub use edit::*;
41pub(crate) use image::*;
42pub use launch::*;
43pub use platforms::*;
44pub use profile::{FrameProfile, FrameProfileHook};
45pub use spatial::*;
46pub use test_support::{MatchMode, NodeQuery};
47pub use types::*;
48
49#[derive(Debug)]
51pub struct AppRuntime {
52 pub root_blueprint: NodeBlueprint,
53 pub ir_graph: strata_dom::UiIrGraph,
54 pub layout_root: LayoutNode,
55 pub display_list: DisplayList,
56 pub spatial_index: SpatialIndex,
57 pub viewport_width: f32,
58 pub viewport_height: f32,
59 pub dpr: f32,
60 pub frame_count: u64,
61 pub active_focus: Option<ActiveInput>,
62 pub input_states: std::collections::HashMap<String, strata_dom::text_input::TextInputState>,
63 pub caret_blink_epoch: std::time::Instant,
64 pub last_caret_blink_state: bool,
65 pub current_cursor: strata_platform::window::CursorIcon,
66 pub drag_selection_active: bool,
67 pub last_click_info: Option<(std::time::Instant, f32, f32, usize)>,
68 pub pending_window_drag: Option<(f32, f32)>,
70 pub last_drag_click: Option<(std::time::Instant, f32, f32)>,
72 pub current_hover_path: Option<Vec<usize>>,
74 pub current_focus_path: Option<Vec<usize>>,
76 pub is_mouse_down: bool,
78 pub is_dark_mode: bool,
80 pub last_mouse_pos: (f32, f32),
82 pub hover_tooltip_text: Option<String>,
84 pub hover_tooltip_path: Option<Vec<usize>>,
86 pub hover_tooltip_anchor: (f32, f32),
88 pub hover_tooltip_since: Option<std::time::Instant>,
90 pub hover_tooltip_visible: bool,
92 pub hover_tooltip_delay: std::time::Duration,
94 pub hover_tooltip_style: strata_platform::HoverTooltipStyle,
96 pub scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
98 pub scroll_offsets_by_id: std::collections::HashMap<String, (f32, f32)>,
100 pub active_scrollbars: Vec<ActiveScrollbar>,
102 pub scrollbar_drag: Option<ScrollbarDrag>,
104 pub active_smooth_scroll: Option<SmoothScrollTracker>,
106 pub last_scroll_interaction: Option<std::time::Instant>,
108 pub applied_scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
110 pub applied_portal_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
112 pub(crate) has_anchored_portals: bool,
114 pub runtime_start_epoch: std::time::Instant,
116 pub transition_manager: strata_style::transition::TransitionManager,
118 pub animation_manager: strata_style::animation::AnimationManager,
120 pub base_node_styles: std::collections::HashMap<u64, ComputedStyle>,
122 pub previous_node_styles: std::collections::HashMap<u64, ComputedStyle>,
124 pub node_paths: std::collections::HashMap<u64, Vec<usize>>,
126 pub path_node_ids: std::collections::HashMap<Vec<usize>, u64>,
128 pub view_transition_manager: crate::view_transition::ViewTransitionManager,
130 pub had_active_animations: bool,
132 pub gpu_path_pipeline: strata_render::GpuPathPipeline,
134 pub(crate) layout_computations: u64,
136 pub(crate) hover_paint_only: bool,
138 pub mcp_cursor: Option<strata_platform::McpCursorState>,
140 pub(crate) cursor_theme: std::sync::OnceLock<strata_platform::CursorTheme>,
142 pub a11y_bridge: strata_a11y::A11yBridge,
144 pub a11y_tree: Option<strata_a11y::A11yTree>,
146 pub a11y_updates_count: u64,
148 pub dynamic_text_bindings: Vec<DynamicTextBinding>,
150 pub dom_mutation_receiver: Option<std::sync::mpsc::Receiver<strata_js::DomMutationRecord>>,
152 #[cfg(feature = "devtools")]
153 pub devtools: Option<strata_devtools::DevTools>,
155 pub csd_controller: strata_platform::CsdController,
157 pub(crate) frame_profile: FrameProfile,
159 pub(crate) paint_dirty: bool,
161 pub(crate) viewport_3d_dirty: bool,
163 pub(crate) tracked_retained_3d: Vec<(strata_render::scene3d::RetainedScene3D, (u64, u64, u64))>,
165 pub(crate) compiles_skipped: u64,
167 pub(crate) frame_profile_hook: Option<FrameProfileHook>,
169 pub(crate) cached_stylesheets: Vec<std::sync::Arc<strata_style::StyleSheet>>,
171 pub pointer_capture_target: Option<(Vec<usize>, bool)>,
173 pub(crate) has_resize_listeners: bool,
175 pub observed_element_sizes: std::collections::HashMap<u64, (f32, f32)>,
177 pub(crate) last_pointer_pos: Option<(f32, f32)>,
179 pub(crate) pending_cursor_warp: Option<(f32, f32)>,
181 pub(crate) last_update_reconciled: bool,
183 pub(crate) active_dom_drag: Option<ActiveDomDrag>,
185}
186
187pub(crate) fn perf_logging_enabled() -> bool {
189 static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
190 *ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
191}
192
193pub(crate) fn perf_log_ms(label: &str, start: std::time::Instant, detail: impl std::fmt::Display) {
195 if perf_logging_enabled() {
196 eprintln!(
197 "[perf] {}: {:.3} ms ({})",
198 label,
199 start.elapsed().as_secs_f64() * 1000.0,
200 detail
201 );
202 }
203}
204
205pub(crate) fn perf_count_layout_nodes(node: &strata_layout::LayoutNode) -> usize {
206 let mut count = 0;
207 let mut stack = vec![node];
208 while let Some(n) = stack.pop() {
209 count += 1;
210 for child in &n.children {
211 stack.push(child);
212 }
213 }
214 count
215}
216
217pub(crate) fn perf_count_blueprint_nodes(node: &NodeBlueprint) -> usize {
218 let mut count = 0;
219 let mut stack = vec![node];
220 while let Some(n) = stack.pop() {
221 count += 1;
222 match n {
223 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
224 for child in children {
225 stack.push(child);
226 }
227 }
228 NodeBlueprint::Text(_) | NodeBlueprint::DynamicText(_) | NodeBlueprint::Empty => {}
229 }
230 }
231 count
232}
233
234impl AppRuntime {
235 pub fn new(root_view: View, viewport_width: f32, viewport_height: f32, dpr: f32) -> Self {
237 #[cfg(target_os = "linux")]
238 strata_platform::init_pango_text_measurement();
239
240 let mut root_blueprint = root_view.root.flatten_fragments();
241 root_blueprint.ensure_entity_ids();
242 let mut ir_graph = Self::build_ir_graph(&root_blueprint);
243
244 let build_start = std::time::Instant::now();
245 let mut layout_root = Self::build_layout_tree(&root_blueprint);
246 if perf_logging_enabled() {
247 perf_log_ms(
248 "build_layout_tree_initial",
249 build_start,
250 format!("{} layout nodes", perf_count_layout_nodes(&layout_root)),
251 );
252 }
253
254 let compute_start = std::time::Instant::now();
255 layout_root.compute_layout(viewport_width, viewport_height);
256 Self::sync_layout_to_ir(&layout_root, &mut ir_graph);
257 let mut spatial_index = SpatialIndex::new();
258 spatial_index.rebuild(&root_blueprint, &layout_root);
259 if perf_logging_enabled() {
260 perf_log_ms(
261 "compute_layout_initial",
262 compute_start,
263 format!("{}x{}", viewport_width, viewport_height),
264 );
265 }
266
267 let mut dynamic_text_bindings = Vec::new();
268 let mut path_buf = Vec::new();
269 Self::collect_dynamic_text_bindings(
270 &root_blueprint,
271 &mut path_buf,
272 &mut dynamic_text_bindings,
273 );
274
275 let mut runtime = Self {
276 root_blueprint,
277 ir_graph,
278 layout_root,
279 display_list: DisplayList::new(),
280 spatial_index,
281 viewport_width,
282 viewport_height,
283 dpr,
284 frame_count: 0,
285 active_focus: None,
286 input_states: std::collections::HashMap::new(),
287 caret_blink_epoch: std::time::Instant::now(),
288 last_caret_blink_state: true,
289 current_cursor: strata_platform::window::CursorIcon::Default,
290 drag_selection_active: false,
291 last_click_info: None,
292 pending_window_drag: None,
293 last_drag_click: None,
294 current_hover_path: None,
295 current_focus_path: None,
296 is_mouse_down: false,
297 is_dark_mode: false,
298 last_mouse_pos: (0.0, 0.0),
299 hover_tooltip_text: None,
300 hover_tooltip_path: None,
301 hover_tooltip_anchor: (0.0, 0.0),
302 hover_tooltip_since: None,
303 hover_tooltip_visible: false,
304 hover_tooltip_delay: std::time::Duration::from_millis(450),
305 hover_tooltip_style: strata_platform::HoverTooltipStyle::default(),
306 scroll_offsets: std::collections::HashMap::new(),
307 scroll_offsets_by_id: std::collections::HashMap::new(),
308 active_scrollbars: Vec::new(),
309 scrollbar_drag: None,
310 active_smooth_scroll: None,
311 last_scroll_interaction: None,
312 applied_scroll_offsets: std::collections::HashMap::new(),
313 applied_portal_offsets: std::collections::HashMap::new(),
314 has_anchored_portals: false,
315 runtime_start_epoch: std::time::Instant::now(),
316 transition_manager: strata_style::transition::TransitionManager::new(),
317 animation_manager: strata_style::animation::AnimationManager::new(),
318 base_node_styles: std::collections::HashMap::new(),
319 previous_node_styles: std::collections::HashMap::new(),
320 node_paths: std::collections::HashMap::new(),
321 path_node_ids: std::collections::HashMap::new(),
322 view_transition_manager: crate::view_transition::ViewTransitionManager::new(),
323 had_active_animations: false,
324 gpu_path_pipeline: strata_render::GpuPathPipeline::new(viewport_width, viewport_height),
325 layout_computations: 1,
326 hover_paint_only: false,
327 mcp_cursor: None,
328 cursor_theme: std::sync::OnceLock::new(),
329 a11y_bridge: strata_a11y::A11yBridge::new(),
330 a11y_tree: None,
331 a11y_updates_count: 0,
332 dynamic_text_bindings,
333 dom_mutation_receiver: None,
334 #[cfg(feature = "devtools")]
335 devtools: None,
336 csd_controller: strata_platform::CsdController::default(),
337 frame_profile: FrameProfile::default(),
338 paint_dirty: true,
339 viewport_3d_dirty: false,
340 tracked_retained_3d: Vec::new(),
341 compiles_skipped: 0,
342 frame_profile_hook: None,
343 cached_stylesheets: Vec::new(),
344 pointer_capture_target: None,
345 has_resize_listeners: false,
346 observed_element_sizes: std::collections::HashMap::new(),
347 last_pointer_pos: None,
348 pending_cursor_warp: None,
349 last_update_reconciled: false,
350 active_dom_drag: None,
351 };
352
353 runtime.has_resize_listeners =
354 Self::blueprint_has_resize_listeners(&runtime.root_blueprint);
355 let initial_sheets = Self::collect_stylesheets_from_blueprint(&runtime.root_blueprint);
356 for sheet in &initial_sheets {
357 runtime.register_keyframes_stylesheet(sheet);
358 }
359 runtime.cached_stylesheets = initial_sheets;
360 runtime.sync_tree_animations(0.0);
361 runtime.apply_viewport_clamps();
362 runtime.apply_scroll_offsets();
363 runtime.dispatch_resize_observers();
364 runtime
365 .spatial_index
366 .rebuild(&runtime.root_blueprint, &runtime.layout_root);
367 runtime.update_accessibility_tree();
368 runtime.compile_display_list();
369 runtime
370 }
371
372 pub fn apply_window_config(&mut self, config: &WindowConfig) -> &mut Self {
375 self.hover_tooltip_delay = config.tooltip_delay;
376 self.hover_tooltip_style = config.tooltip_style;
377 if self.hover_tooltip_visible {
378 self.paint_dirty = true;
379 }
380 self
381 }
382
383 pub fn set_hover_tooltip_delay(&mut self, delay: std::time::Duration) -> &mut Self {
385 self.hover_tooltip_delay = delay;
386 self
387 }
388
389 pub fn set_hover_tooltip_delay_ms(&mut self, delay_ms: u64) -> &mut Self {
391 self.hover_tooltip_delay = std::time::Duration::from_millis(delay_ms);
392 self
393 }
394
395 pub fn hover_tooltip_delay(&self) -> std::time::Duration {
397 self.hover_tooltip_delay
398 }
399
400 pub fn set_hover_tooltip_style(
402 &mut self,
403 style: strata_platform::HoverTooltipStyle,
404 ) -> &mut Self {
405 self.hover_tooltip_style = style;
406 if self.hover_tooltip_visible {
407 self.paint_dirty = true;
408 }
409 self
410 }
411
412 pub fn hover_tooltip_style(&self) -> strata_platform::HoverTooltipStyle {
414 self.hover_tooltip_style
415 }
416
417 pub fn tick_frame(&mut self) -> &DisplayList {
419 self.frame_count += 1;
420 self.unapply_scroll_offsets();
421 let compute_start = std::time::Instant::now();
422 self.layout_root
423 .compute_layout(self.viewport_width, self.viewport_height);
424 Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
425 self.layout_computations += 1;
426 self.frame_profile.layout += compute_start.elapsed();
427 if perf_logging_enabled() {
428 perf_log_ms(
429 "compute_layout_tick",
430 compute_start,
431 format!(
432 "{} layout nodes",
433 perf_count_layout_nodes(&self.layout_root)
434 ),
435 );
436 }
437 self.apply_viewport_clamps();
438 self.apply_scroll_offsets();
439 self.dispatch_resize_observers();
440 self.spatial_index
441 .rebuild(&self.root_blueprint, &self.layout_root);
442 self.update_accessibility_tree();
443 self.compile_display_list();
444 &self.display_list
445 }
446
447 pub fn interaction_context(&self) -> InteractionContext<'_> {
449 InteractionContext {
450 hovered_path: self.current_hover_path.as_deref(),
451 focused_path: self.current_focus_path.as_deref(),
452 is_mouse_down: self.is_mouse_down,
453 is_dark_mode: self.is_dark_mode,
454 }
455 }
456
457 pub fn set_dark_mode(&mut self, is_dark: bool) -> bool {
459 if self.is_dark_mode != is_dark {
460 self.is_dark_mode = is_dark;
461 self.rebuild_layout_tree();
462 true
463 } else {
464 false
465 }
466 }
467
468 pub fn set_focus_path(&mut self, path: Option<Vec<usize>>) -> bool {
470 if self.current_focus_path != path {
471 self.current_focus_path = path;
472 self.rebuild_layout_tree();
473 true
474 } else {
475 false
476 }
477 }
478
479 pub fn rebuild_spatial_index(&mut self) {
481 self.spatial_index
482 .rebuild(&self.root_blueprint, &self.layout_root);
483 }
484
485 pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<strata_primitives::EntityId> {
487 self.spatial_index.query_entity_at_point(px, py)
488 }
489
490 pub fn query_event_at_point(
492 &self,
493 px: f32,
494 py: f32,
495 event_type: strata_dom::EventType,
496 ) -> Option<(
497 strata_primitives::EntityId,
498 std::rc::Rc<dyn Fn(strata_dom::Event)>,
499 strata_layout::Rect,
500 )> {
501 self.spatial_index.query_event_at_point(px, py, event_type)
502 }
503
504 pub fn find_layout_by_entity(
506 &self,
507 entity_id: strata_primitives::EntityId,
508 ) -> Option<&LayoutNode> {
509 self.layout_root.find_by_entity_id(entity_id)
510 }
511
512 pub fn find_layout_mut_by_entity(
514 &mut self,
515 entity_id: strata_primitives::EntityId,
516 ) -> Option<&mut LayoutNode> {
517 self.layout_root.find_by_entity_id_mut(entity_id)
518 }
519
520 pub fn find_blueprint_by_entity(
522 &self,
523 entity_id: strata_primitives::EntityId,
524 ) -> Option<&NodeBlueprint> {
525 self.root_blueprint.find_by_entity_id(entity_id)
526 }
527
528 pub fn query_element_rect(&self, element_id: &str) -> Option<strata_layout::Rect> {
530 fn find_rec(node: &LayoutNode, target_id: &str) -> Option<strata_layout::Rect> {
531 if node.element_id.as_deref() == Some(target_id) {
532 return Some(node.geometry.border_box);
533 }
534 for child in &node.children {
535 if let Some(rect) = find_rec(child, target_id) {
536 return Some(rect);
537 }
538 }
539 None
540 }
541 find_rec(&self.layout_root, element_id)
542 }
543
544 pub fn warp_cursor(&mut self, x: f32, y: f32) {
547 self.last_pointer_pos = Some((x, y));
548 self.pending_cursor_warp = Some((x, y));
549 #[cfg(target_os = "linux")]
550 strata_platform::gtk_warp_cursor(x as f64, y as f64);
551 }
552
553 pub fn set_cursor_position(&mut self, x: f32, y: f32) {
555 self.warp_cursor(x, y);
556 }
557
558 pub fn update_element_flex(
561 &mut self,
562 element_id: &str,
563 flex_grow: f32,
564 flex_shrink: f32,
565 flex_basis: Option<strata_style::types::Dimension>,
566 ) -> bool {
567 fn update_rec(
568 node: &mut LayoutNode,
569 target_id: &str,
570 flex_grow: f32,
571 flex_shrink: f32,
572 flex_basis: Option<strata_style::types::Dimension>,
573 ) -> bool {
574 if node.element_id.as_deref() == Some(target_id) {
575 node.style.flex_grow = flex_grow;
576 node.style.flex_shrink = flex_shrink;
577 if let Some(basis) = flex_basis {
578 node.style.flex_basis = basis;
579 }
580 node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
581 return true;
582 }
583 let mut changed = false;
584 for child in &mut node.children {
585 if update_rec(child, target_id, flex_grow, flex_shrink, flex_basis) {
586 changed = true;
587 }
588 }
589 if changed {
590 node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
591 }
592 changed
593 }
594 update_rec(
595 &mut self.layout_root,
596 element_id,
597 flex_grow,
598 flex_shrink,
599 flex_basis,
600 )
601 }
602
603 pub fn update_split_ratios(&mut self, updates: &[(&str, f32)]) -> bool {
606 let mut any_changed = false;
607 for &(id, ratio) in updates {
608 if self.update_element_flex(id, ratio, 1.0, None) {
609 any_changed = true;
610 }
611 }
612 if any_changed {
613 self.relayout_in_place();
614 }
615 any_changed
616 }
617
618 pub fn relayout_in_place(&mut self) {
621 self.unapply_scroll_offsets();
622 let compute_start = std::time::Instant::now();
623 self.layout_root
624 .compute_layout(self.viewport_width, self.viewport_height);
625 self.layout_computations += 1;
626 self.frame_profile.layout += compute_start.elapsed();
627 self.apply_viewport_clamps();
628 self.apply_scroll_offsets();
629 self.dispatch_resize_observers();
630 self.spatial_index
631 .rebuild(&self.root_blueprint, &self.layout_root);
632 self.paint_dirty = true;
633 self.compile_display_list();
634 }
635
636 pub(crate) fn blueprint_has_resize_listeners(bp: &NodeBlueprint) -> bool {
638 match bp {
639 NodeBlueprint::Element {
640 attributes,
641 children,
642 ..
643 } => {
644 attributes.iter().any(|a| {
645 matches!(
646 a,
647 strata_dom::Attribute::EventListener {
648 event: strata_dom::EventType::Resize,
649 ..
650 }
651 )
652 }) || children.iter().any(Self::blueprint_has_resize_listeners)
653 }
654 NodeBlueprint::Fragment(children) => {
655 children.iter().any(Self::blueprint_has_resize_listeners)
656 }
657 _ => false,
658 }
659 }
660
661 pub fn dispatch_resize_observers(&mut self) -> bool {
664 if !self.has_resize_listeners {
665 return false;
666 }
667 let mut pending: Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)> =
668 Vec::new();
669 let mut active_ids = std::collections::HashSet::new();
670 let mut path = Vec::new();
671
672 #[allow(clippy::too_many_arguments)]
673 fn collect_rec(
674 bp: &NodeBlueprint,
675 layout: &LayoutNode,
676 path: &mut Vec<usize>,
677 path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
678 observed: &mut std::collections::HashMap<u64, (f32, f32)>,
679 active_ids: &mut std::collections::HashSet<u64>,
680 pending: &mut Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)>,
681 ) {
682 if let NodeBlueprint::Element {
683 attributes,
684 children,
685 ..
686 } = bp
687 {
688 let node_id = path_node_ids
689 .get(path)
690 .copied()
691 .unwrap_or_else(|| path_to_node_id(path));
692 let mut resize_handlers = Vec::new();
693 for attr in attributes {
694 if let strata_dom::Attribute::EventListener {
695 event: strata_dom::EventType::Resize,
696 handler,
697 } = attr
698 {
699 resize_handlers.push(handler.clone());
700 }
701 }
702 if !resize_handlers.is_empty() {
703 active_ids.insert(node_id);
704 let w = layout.geometry.border_box.width;
705 let h = layout.geometry.border_box.height;
706 let changed = match observed.get(&node_id) {
707 Some(&(pw, ph)) => (w - pw).abs() > 0.25 || (h - ph).abs() > 0.25,
708 None => true,
709 };
710 if changed {
711 observed.insert(node_id, (w, h));
712 for handler in resize_handlers {
713 pending.push((handler, layout.geometry.border_box));
714 }
715 }
716 }
717 for (idx, child_layout) in layout.children.iter().enumerate() {
718 if let Some(child_bp) = children.get(idx) {
719 path.push(idx);
720 collect_rec(
721 child_bp,
722 child_layout,
723 path,
724 path_node_ids,
725 observed,
726 active_ids,
727 pending,
728 );
729 path.pop();
730 }
731 }
732 }
733 }
734
735 collect_rec(
736 &self.root_blueprint,
737 &self.layout_root,
738 &mut path,
739 &self.path_node_ids,
740 &mut self.observed_element_sizes,
741 &mut active_ids,
742 &mut pending,
743 );
744 self.observed_element_sizes
745 .retain(|id, _| active_ids.contains(id));
746
747 if pending.is_empty() {
748 return false;
749 }
750 for (handler, rect) in pending {
751 let mut ev = strata_dom::Event::new(strata_dom::EventType::Resize);
752 ev.client_x = rect.x as f64;
753 ev.client_y = rect.y as f64;
754 ev.offset_x = rect.width as f64;
755 ev.offset_y = rect.height as f64;
756 ev.width = rect.width as f64;
757 ev.height = rect.height as f64;
758 handler(ev);
759 }
760 true
761 }
762
763 fn element_attr_value<'a>(
764 attrs: &'a [strata_dom::Attribute],
765 key_name: &str,
766 ) -> Option<&'a str> {
767 attrs.iter().find_map(|a| match a {
768 strata_dom::Attribute::Property { key, value } if key == key_name => {
769 Some(value.as_str())
770 }
771 _ => None,
772 })
773 }
774
775 fn attributes_visually_equal(a: &[strata_dom::Attribute], b: &[strata_dom::Attribute]) -> bool {
776 let mut iter_a = a.iter().filter(|attr| {
777 !matches!(
778 attr,
779 strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
780 )
781 });
782 let mut iter_b = b.iter().filter(|attr| {
783 !matches!(
784 attr,
785 strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
786 )
787 });
788 loop {
789 match (iter_a.next(), iter_b.next()) {
790 (None, None) => return true,
791 (Some(x), Some(y)) => match (x, y) {
792 (
793 strata_dom::Attribute::Property { key: k1, value: v1 },
794 strata_dom::Attribute::Property { key: k2, value: v2 },
795 ) if k1 == k2 && v1 == v2 => {}
796 (
797 strata_dom::Attribute::DirectStyle(d1),
798 strata_dom::Attribute::DirectStyle(d2),
799 ) if std::rc::Rc::ptr_eq(d1, d2) => {}
800 (
801 strata_dom::Attribute::ScenePayload(s1),
802 strata_dom::Attribute::ScenePayload(s2),
803 ) if std::sync::Arc::ptr_eq(s1, s2) => {}
804 _ => return false,
805 },
806 _ => return false,
807 }
808 }
809 }
810
811 fn inherited_style_equal(
812 a: &strata_style::ComputedStyle,
813 b: &strata_style::ComputedStyle,
814 ) -> bool {
815 a.color == b.color
816 && a.font_family == b.font_family
817 && a.font_size == b.font_size
818 && a.root_font_size == b.root_font_size
819 && a.font_weight == b.font_weight
820 && a.font_style == b.font_style
821 && a.text_align == b.text_align
822 && a.line_height == b.line_height
823 && a.letter_spacing == b.letter_spacing
824 && a.text_decoration == b.text_decoration
825 && a.text_transform == b.text_transform
826 && a.text_overflow == b.text_overflow
827 && a.white_space == b.white_space
828 && a.cursor == b.cursor
829 && a.user_select == b.user_select
830 && a.pointer_events == b.pointer_events
831 && a.visibility == b.visibility
832 && a.caret_color == b.caret_color
833 && a.border_collapse == b.border_collapse
834 && a.border_spacing == b.border_spacing
835 && a.caption_side == b.caption_side
836 && a.custom_properties == b.custom_properties
837 }
838
839 fn blueprint_visually_equal(a: &NodeBlueprint, b: &NodeBlueprint) -> bool {
840 match (a, b) {
841 (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => t1 == t2,
842 (NodeBlueprint::Empty, NodeBlueprint::Empty) => true,
843 (
844 NodeBlueprint::Element {
845 tag: t1,
846 classes: cls1,
847 attributes: a1,
848 children: c1,
849 },
850 NodeBlueprint::Element {
851 tag: t2,
852 classes: cls2,
853 attributes: a2,
854 children: c2,
855 },
856 ) => {
857 t1 == t2
858 && cls1 == cls2
859 && c1.len() == c2.len()
860 && Self::attributes_visually_equal(a1, a2)
861 && c1
862 .iter()
863 .zip(c2.iter())
864 .all(|(x, y)| Self::blueprint_visually_equal(x, y))
865 }
866 _ => false,
867 }
868 }
869
870 fn reconcile_layout_subtree(
876 old_bp: &NodeBlueprint,
877 new_bp: &NodeBlueprint,
878 layout_node: &mut LayoutNode,
879 parent_style: Option<&strata_style::ComputedStyle>,
880 parent_inherited_changed: bool,
881 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
882 ctx: &crate::runtime::InteractionContext,
883 ) -> Option<bool> {
884 match (old_bp, new_bp) {
885 (NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => {
886 if t1 == t2 && !parent_inherited_changed {
887 Some(false)
888 } else {
889 *layout_node = Self::build_text_leaf_layout_node(t2.clone(), parent_style);
890 Some(true)
891 }
892 }
893 (
894 NodeBlueprint::Element { tag: t1, .. },
895 NodeBlueprint::Element { tag: t2, .. },
896 ) if t1 == t2
897 && matches!(
898 t1,
899 strata_dom::Tag::Svg
900 | strata_dom::Tag::Path
901 | strata_dom::Tag::Input
902 | strata_dom::Tag::Img
903 ) =>
904 {
905 if !parent_inherited_changed && Self::blueprint_visually_equal(old_bp, new_bp) {
906 if let Some(eid) = new_bp.entity_id() {
907 layout_node.entity_id = eid;
908 }
909 Some(false)
910 } else {
911 None
912 }
913 }
914 (
915 NodeBlueprint::Element {
916 tag: t1,
917 classes: cls1,
918 attributes: a1,
919 children: c1,
920 },
921 NodeBlueprint::Element {
922 tag: t2,
923 classes: cls2,
924 attributes: a2,
925 children: c2,
926 },
927 ) if t1 == t2
928 && !layout_node.is_top_layer
929 && layout_node.children.len() == c1.len()
930 && Self::element_attr_value(a1, "key") == Self::element_attr_value(a2, "key")
931 && Self::element_attr_value(a1, "id") == Self::element_attr_value(a2, "id") =>
932 {
933 let self_props_changed = cls1 != cls2 || !Self::attributes_visually_equal(a1, a2);
934 let single_text_changed = c1.len() == 1
935 && c2.len() == 1
936 && matches!(
937 (&c1[0], &c2[0]),
938 (NodeBlueprint::Text(x), NodeBlueprint::Text(y)) if x != y
939 );
940
941 let (self_rewritten, child_inherited_changed) =
942 if self_props_changed || parent_inherited_changed || single_text_changed {
943 let shallow_bp = NodeBlueprint::Element {
944 tag: *t2,
945 classes: cls2.clone(),
946 attributes: a2.clone(),
947 children: Vec::new(),
948 };
949 let mut path_buf = Vec::new();
950 let mut ancestors = Vec::new();
951 let mut updated = Self::build_layout_tree_full(
952 &shallow_bp,
953 parent_style,
954 &mut path_buf,
955 ctx,
956 stylesheets,
957 &mut ancestors,
958 &[],
959 true,
960 (false, false, false),
961 );
962 Self::apply_single_text_inline_intrinsic_sizing(&mut updated.style, c2);
963 if let Some(eid) = new_bp.entity_id() {
964 updated.entity_id = eid;
965 }
966 let inh_changed =
967 !Self::inherited_style_equal(&layout_node.style, &updated.style);
968 updated.children = std::mem::take(&mut layout_node.children);
969 *layout_node = updated;
970 (true, inh_changed)
971 } else {
972 if let Some(eid) = new_bp.entity_id() {
973 layout_node.entity_id = eid;
974 }
975 (false, false)
976 };
977
978 let parent_style_for_children = layout_node.style.clone();
979 let mut children_changed = c1.len() != c2.len();
980 let common = c1.len().min(c2.len());
981 for i in 0..common {
982 match Self::reconcile_layout_subtree(
983 &c1[i],
984 &c2[i],
985 &mut layout_node.children[i],
986 Some(&parent_style_for_children),
987 child_inherited_changed,
988 stylesheets,
989 ctx,
990 ) {
991 Some(false) => {}
992 Some(true) => children_changed = true,
993 None => {
994 let mut path_buf = Vec::new();
995 let mut ancestors = Vec::new();
996 layout_node.children[i] = Self::build_layout_tree_full(
997 &c2[i],
998 Some(&parent_style_for_children),
999 &mut path_buf,
1000 ctx,
1001 stylesheets,
1002 &mut ancestors,
1003 &[],
1004 i + 1 == c2.len(),
1005 (false, false, false),
1006 );
1007 children_changed = true;
1008 }
1009 }
1010 }
1011 if c2.len() < c1.len() {
1012 layout_node.children.truncate(c2.len());
1013 } else if c2.len() > c1.len() {
1014 for (offset, nc) in c2[common..].iter().enumerate() {
1015 let idx = common + offset;
1016 let mut path_buf = Vec::new();
1017 let mut ancestors = Vec::new();
1018 layout_node.children.push(Self::build_layout_tree_full(
1019 nc,
1020 Some(&parent_style_for_children),
1021 &mut path_buf,
1022 ctx,
1023 stylesheets,
1024 &mut ancestors,
1025 &[],
1026 idx + 1 == c2.len(),
1027 (false, false, false),
1028 ));
1029 }
1030 }
1031
1032 if self_rewritten || children_changed {
1033 layout_node.inline_items.clear();
1034 layout_node.line_boxes.clear();
1035 layout_node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
1036 Some(true)
1037 } else {
1038 Some(false)
1039 }
1040 }
1041 _ => None,
1042 }
1043 }
1044
1045 pub fn update_view(&mut self, new_view: View) {
1048 self.unapply_scroll_offsets();
1049 self.applied_scroll_offsets.clear();
1050 self.applied_portal_offsets.clear();
1051 let mut next_blueprint = new_view.root.flatten_fragments();
1052 next_blueprint.ensure_entity_ids();
1053 let old_blueprint = std::mem::replace(&mut self.root_blueprint, next_blueprint);
1054 self.has_resize_listeners = Self::blueprint_has_resize_listeners(&self.root_blueprint);
1055 self.ir_graph = Self::build_ir_graph(&self.root_blueprint);
1056 let sheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
1057 let sheets_unchanged = self.cached_stylesheets == sheets;
1058 if !sheets_unchanged {
1059 for sheet in &sheets {
1060 self.register_keyframes_stylesheet(sheet);
1061 }
1062 self.cached_stylesheets = sheets;
1063 }
1064 let build_start = std::time::Instant::now();
1065 let hover_safe = self.hover_is_paint_only()
1066 || self.current_hover_path.as_deref().is_none_or(|p| {
1067 !Self::node_path_has_hover_effects_with_sheets(
1068 &old_blueprint,
1069 p,
1070 &self.cached_stylesheets,
1071 ) && !Self::node_path_has_hover_effects_with_sheets(
1072 &self.root_blueprint,
1073 p,
1074 &self.cached_stylesheets,
1075 )
1076 });
1077 let reconciled = if self.cached_stylesheets.is_empty()
1078 && sheets_unchanged
1079 && hover_safe
1080 && self.current_focus_path.is_none()
1081 {
1082 let ctx = crate::runtime::InteractionContext {
1083 hovered_path: None,
1084 focused_path: None,
1085 is_mouse_down: self.is_mouse_down,
1086 is_dark_mode: self.is_dark_mode,
1087 };
1088 Self::reconcile_layout_subtree(
1089 &old_blueprint,
1090 &self.root_blueprint,
1091 &mut self.layout_root,
1092 None,
1093 false,
1094 &self.cached_stylesheets,
1095 &ctx,
1096 )
1097 .is_some()
1098 } else {
1099 false
1100 };
1101 if !reconciled {
1102 let ctx = self.interaction_context();
1103 self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
1104 }
1105 self.last_update_reconciled = reconciled;
1106 if perf_logging_enabled() {
1107 perf_log_ms(
1108 "build_layout_tree_update",
1109 build_start,
1110 format!(
1111 "{} blueprint nodes -> {} layout nodes (reconciled={})",
1112 perf_count_blueprint_nodes(&self.root_blueprint),
1113 perf_count_layout_nodes(&self.layout_root),
1114 reconciled
1115 ),
1116 );
1117 }
1118 self.sync_active_input_layout();
1119 self.dynamic_text_bindings.clear();
1120 let mut path_buf = Vec::new();
1121 Self::collect_dynamic_text_bindings(
1122 &self.root_blueprint,
1123 &mut path_buf,
1124 &mut self.dynamic_text_bindings,
1125 );
1126 let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
1127 let sync_start = std::time::Instant::now();
1128 self.sync_tree_animations(now_ms);
1129 if perf_logging_enabled() {
1130 perf_log_ms("sync_tree_animations", sync_start, "update_view");
1131 }
1132 self.refresh_hover_tooltip_after_view_update();
1133 self.tick_frame();
1134 }
1135
1136 pub fn sync_dynamic_text(&mut self) -> bool {
1140 if self.dynamic_text_bindings.is_empty() {
1141 return false;
1142 }
1143
1144 let mut changed = false;
1145 for binding in &mut self.dynamic_text_bindings {
1146 let new_text = (binding.closure)();
1147 if new_text != binding.last_value {
1148 binding.last_value = new_text.clone();
1149 if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &binding.path)
1150 {
1151 let is_mono = strata_layout::is_monospace_family(node.style.font_family);
1152 let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
1153 &new_text,
1154 node.style.font_size,
1155 node.style.line_height,
1156 None,
1157 is_mono,
1158 node.style.font_family,
1159 node.style.font_weight,
1160 node.style.font_style,
1161 );
1162 node.style.width = strata_style::types::Dimension::Px(w);
1163 node.style.height = strata_style::types::Dimension::Px(h);
1164 node.geometry.content_box.width = w;
1165 node.geometry.content_box.height = h;
1166 node.text = Some(new_text);
1167 node.layout_cache.is_valid = false;
1168 changed = true;
1169 }
1170 }
1171 }
1172
1173 if changed {
1174 self.tick_frame();
1175 true
1176 } else {
1177 false
1178 }
1179 }
1180
1181 pub fn cursor_theme(&self) -> &strata_platform::CursorTheme {
1184 self.cursor_theme
1185 .get_or_init(strata_platform::CursorTheme::load_active)
1186 }
1187
1188 pub fn mark_viewport_3d_dirty(&mut self) {
1190 self.viewport_3d_dirty = true;
1191 }
1192
1193 pub fn poll_retained_3d_dirty(&self) -> bool {
1196 if self.viewport_3d_dirty {
1197 return true;
1198 }
1199 self.tracked_retained_3d
1200 .iter()
1201 .any(|(handle, last_gens)| handle.generations() != *last_gens)
1202 }
1203
1204 pub fn acknowledge_retained_3d_presented(&mut self) {
1206 self.viewport_3d_dirty = false;
1207 for (handle, last_gens) in &mut self.tracked_retained_3d {
1208 *last_gens = handle.generations();
1209 }
1210 }
1211
1212 pub fn has_uncapped_canvas3d(&self) -> bool {
1214 fn walk(node: &NodeBlueprint) -> bool {
1215 if let NodeBlueprint::Element {
1216 attributes,
1217 children,
1218 ..
1219 } = node
1220 {
1221 if attributes.iter().any(|a| {
1222 matches!(
1223 a,
1224 strata_dom::Attribute::Property { key, value }
1225 if key == "data-strata-uncapped" && value == "true"
1226 )
1227 }) {
1228 return true;
1229 }
1230 if children.iter().any(walk) {
1231 return true;
1232 }
1233 }
1234 false
1235 }
1236 walk(&self.root_blueprint)
1237 }
1238
1239 pub fn mark_paint_dirty(&mut self) {
1241 self.paint_dirty = true;
1242 }
1243
1244 pub fn is_paint_dirty(&self) -> bool {
1246 self.paint_dirty
1247 }
1248
1249 pub fn compiles_skipped(&self) -> u64 {
1251 self.compiles_skipped
1252 }
1253
1254 pub fn compile_display_list_if_dirty(&mut self) -> bool {
1257 if !self.paint_dirty {
1258 self.compiles_skipped += 1;
1259 return false;
1260 }
1261 self.compile_display_list();
1262 true
1263 }
1264
1265 pub fn compile_display_list(&mut self) {
1267 let compile_start = std::time::Instant::now();
1268 let viewport = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
1269 Some(strata_layout::Rect::new(
1270 0.0,
1271 0.0,
1272 self.viewport_width,
1273 self.viewport_height,
1274 ))
1275 } else {
1276 None
1277 };
1278 self.display_list = strata_render::compositor::Compositor::build_display_list_with_viewport(
1279 &self.layout_root,
1280 viewport,
1281 );
1282 self.tracked_retained_3d.clear();
1283 for cmd in &self.display_list.commands {
1284 if let strata_render::compositor::DrawCommand::DrawViewport3D { scene, .. } = cmd {
1285 if let Some(handle) = scene.retained_handle() {
1286 self.tracked_retained_3d
1287 .push((handle.clone(), handle.generations()));
1288 }
1289 }
1290 }
1291 self.render_scrollbars();
1292 self.render_active_input_caret();
1293 self.render_hover_tooltip();
1294 self.gpu_path_pipeline
1295 .resize(self.viewport_width, self.viewport_height);
1296 self.gpu_path_pipeline
1297 .compile_frame(&self.display_list, None);
1298 self.frame_profile.compile += compile_start.elapsed();
1299 self.paint_dirty = false;
1300
1301 static COMPILE_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1302 let frame = COMPILE_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1303 if frame < 6 || frame.is_multiple_of(120) {
1304 perf_log_ms(
1305 "compile_display_list",
1306 compile_start,
1307 format!(
1308 "frame {} {}x{} {} commands",
1309 frame,
1310 self.viewport_width,
1311 self.viewport_height,
1312 self.display_list.commands.len()
1313 ),
1314 );
1315 }
1316 }
1317
1318 #[inline]
1320 pub fn gpu_path_segments(&self) -> &[strata_render::gpu_path::GpuPathSegment] {
1321 &self.gpu_path_pipeline.batch.segments
1322 }
1323
1324 #[inline]
1326 pub fn gpu_path_uniform_bytes(&self) -> &[u8] {
1327 self.gpu_path_pipeline.uniform_bytes()
1328 }
1329
1330 pub fn step_event(&mut self, event: &PlatformEvent) -> bool {
1333 #[cfg(feature = "devtools")]
1334 if let Some(ref mut dt) = self.devtools {
1335 if strata_devtools::DevToolsEventInterceptor::intercept(&mut dt.hud, event) {
1336 return true;
1337 }
1338 }
1339
1340 let mut needs_redraw = match event {
1341 PlatformEvent::WindowResized { width, height } => {
1342 self.viewport_width = *width as f32;
1343 self.viewport_height = *height as f32;
1344 #[cfg(feature = "devtools")]
1345 if let Some(ref mut dt) = self.devtools {
1346 dt.hud
1347 .update_bounds(self.viewport_width, self.viewport_height);
1348 }
1349 self.tick_frame();
1350 true
1351 }
1352 PlatformEvent::ScaleFactorChanged { scale_factor } => {
1353 self.dpr = *scale_factor;
1354 self.tick_frame();
1355 true
1356 }
1357 PlatformEvent::WindowFocused(_) => false,
1358 PlatformEvent::WindowCloseRequested => false,
1359 PlatformEvent::Scroll {
1360 delta_x, delta_y, ..
1361 } => {
1362 let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1363 let (wheel_handled, scroll_changed) = self.dispatch_smooth_scroll_action(
1364 self.last_mouse_pos.0,
1365 self.last_mouse_pos.1,
1366 *delta_x,
1367 *delta_y,
1368 );
1369 if wheel_handled {
1370 self.rebuild_layout_tree();
1371 true
1372 } else {
1373 scroll_changed || tooltip_dismissed
1374 }
1375 }
1376 PlatformEvent::AnimationTick => {
1377 let scroll_changed = self.poll_smooth_scroll();
1378 let anim_changed = self.poll_animations();
1379 let caret_changed = self.poll_caret_blink();
1380 let tooltip_changed = self.poll_hover_tooltip();
1381 scroll_changed || anim_changed || caret_changed || tooltip_changed
1382 }
1383 PlatformEvent::MouseMove { x, y } => {
1384 self.last_mouse_pos = (*x, *y);
1385 let cur = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, *x, *y);
1386 self.current_cursor = cur;
1387 let hover_changed = self.update_hover(*x, *y);
1388 self.dispatch_pointer_move_action(*x, *y).needs_redraw() || hover_changed
1389 }
1390 PlatformEvent::MouseDown { button, x, y } => {
1391 let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1392 let btn_idx = button.to_button_index();
1393 if *button == strata_platform::MouseButton::Left {
1394 self.is_mouse_down = true;
1395 }
1396 let action = self.dispatch_pointer_down_action_with_button_and_modifiers(
1397 *x,
1398 *y,
1399 btn_idx,
1400 Default::default(),
1401 );
1402 let click_invoked = if *button != strata_platform::MouseButton::Right {
1403 self.dispatch_mouse_click(*x, *y, btn_idx, 1)
1404 } else {
1405 self.dispatch_context_menu(*x, *y)
1406 };
1407 let dynamic_updated = self.sync_dynamic_text();
1408 if action.needs_rebuild() || click_invoked || dynamic_updated {
1409 self.rebuild_layout_tree();
1410 true
1411 } else {
1412 tooltip_dismissed || action.needs_redraw() || self.restyle_for_active_change()
1413 }
1414 }
1415 PlatformEvent::MouseUp { button, x, y } => {
1416 let btn_idx = button.to_button_index();
1417 let was_mouse_down = self.is_mouse_down;
1418 if *button == strata_platform::MouseButton::Left {
1419 self.is_mouse_down = false;
1420 }
1421 let action = self.dispatch_pointer_up_action_with_button(*x, *y, btn_idx);
1422 if action.needs_rebuild() {
1423 self.rebuild_layout_tree();
1424 true
1425 } else if was_mouse_down {
1426 action.needs_redraw() || self.restyle_for_active_change()
1427 } else {
1428 action.needs_redraw()
1429 }
1430 }
1431 PlatformEvent::CursorLeft => {
1432 self.is_mouse_down = false;
1433 self.current_cursor = strata_platform::window::CursorIcon::Default;
1434 self.clear_hover()
1435 }
1436 PlatformEvent::KeyDown { .. }
1437 | PlatformEvent::KeyUp { .. }
1438 | PlatformEvent::ReceivedCharacter(_)
1439 | PlatformEvent::ImePreedit { .. }
1440 | PlatformEvent::ImeCommit(_) => {
1441 let tooltip_dismissed = matches!(event, PlatformEvent::KeyDown { .. })
1442 && self.dismiss_hover_tooltip_and_repaint();
1443 let res = self.dispatch_key_event(event);
1444 let dynamic_updated = self.sync_dynamic_text();
1445 tooltip_dismissed || res.needs_redraw() || dynamic_updated
1446 }
1447 PlatformEvent::FileDrop(paths) => {
1448 let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
1449 let drop_handled = self.dispatch_file_drop(paths.clone());
1450 let dynamic_updated = self.sync_dynamic_text();
1451 if drop_handled || dynamic_updated {
1452 self.rebuild_layout_tree();
1453 true
1454 } else {
1455 tooltip_dismissed
1456 }
1457 }
1458 _ => false,
1459 };
1460
1461 if self.poll_dom_mutations(None) {
1462 needs_redraw = true;
1463 }
1464
1465 if needs_redraw {
1466 self.paint_dirty = true;
1467 }
1468 needs_redraw
1469 }
1470
1471 pub fn layout_computations(&self) -> u64 {
1473 self.layout_computations
1474 }
1475
1476 pub fn last_update_reconciled(&self) -> bool {
1478 self.last_update_reconciled
1479 }
1480
1481 pub fn frame_profile(&self) -> FrameProfile {
1483 self.frame_profile
1484 }
1485
1486 pub fn set_frame_profile_hook(&mut self, hook: Option<Box<dyn FnMut(&FrameProfile)>>) {
1488 self.frame_profile_hook = hook.map(FrameProfileHook);
1489 }
1490
1491 pub fn record_raster_time(&mut self, elapsed: std::time::Duration) {
1493 self.frame_profile.raster += elapsed;
1494 }
1495
1496 pub fn record_present_time(&mut self, elapsed: std::time::Duration) {
1498 self.frame_profile.present += elapsed;
1499 }
1500
1501 pub fn finish_frame_profile(&mut self) -> FrameProfile {
1504 let done = std::mem::take(&mut self.frame_profile);
1505 if let Some(hook) = self.frame_profile_hook.as_mut() {
1506 (hook.0)(&done);
1507 }
1508 done
1509 }
1510
1511 pub fn render_frame<P: SurfacePresenter>(
1513 &mut self,
1514 compositor: &mut SwapchainCompositor,
1515 presenter: &mut P,
1516 force_redraw: bool,
1517 ) -> Result<bool, PresentError> {
1518 #[cfg(feature = "devtools")]
1519 let frame_start = std::time::Instant::now();
1520
1521 let retained_3d_dirty = self.poll_retained_3d_dirty();
1522 if self.paint_dirty || self.frame_count == 0 || force_redraw {
1523 self.tick_frame();
1524 } else {
1525 self.compiles_skipped += 1;
1526 }
1527
1528 #[cfg(feature = "devtools")]
1529 if let Some(ref mut dt) = self.devtools {
1530 if dt.hud.state.is_visible {
1531 dt.hud
1532 .render_overlay(Some(&dt.profiler), &mut self.display_list);
1533 }
1534 }
1535
1536 #[cfg(feature = "devtools")]
1537 let submit_start = std::time::Instant::now();
1538
1539 let present_start = std::time::Instant::now();
1540 let res = compositor.render_and_present(
1541 &self.display_list,
1542 presenter,
1543 force_redraw || retained_3d_dirty,
1544 );
1545 self.acknowledge_retained_3d_presented();
1546 self.frame_profile.present += present_start.elapsed();
1547 self.finish_frame_profile();
1548
1549 #[cfg(feature = "devtools")]
1550 if let Some(ref mut dt) = self.devtools {
1551 let submit_dur = submit_start.elapsed().as_micros() as u32;
1552 let total_dur = frame_start.elapsed().as_micros() as u32;
1553 let sample = strata_devtools::FrameTimingSample {
1554 frame_index: self.frame_count,
1555 vsync_wait_us: 0,
1556 input_dispatch_us: 100,
1557 signal_drain_us: 150,
1558 parallel_reconcile_us: 200,
1559 style_cascade_us: 250,
1560 layout_solve_us: 300,
1561 display_list_build_us: 350,
1562 gpu_submit_us: submit_dur,
1563 gpu_raster_duration_us: submit_dur.max(500),
1564 total_cpu_frame_us: total_dur,
1565 frame_budget_us: 16666,
1566 layout_shift_score: 0.0,
1567 };
1568 dt.profiler.record_sample(sample);
1569 dt.cdp_dispatcher.update_from_ir(
1570 &self.ir_graph,
1571 &self.base_node_styles,
1572 self.frame_count,
1573 self.layout_computations,
1574 );
1575 }
1576
1577 res
1578 }
1579
1580 #[cfg(feature = "devtools")]
1581 pub fn enable_devtools(&mut self) -> &mut strata_devtools::DevTools {
1583 if self.devtools.is_none() {
1584 let mut dt = strata_devtools::DevTools::new();
1585 dt.hud
1586 .update_bounds(self.viewport_width, self.viewport_height);
1587 self.devtools = Some(dt);
1588 }
1589 self.devtools.as_mut().unwrap()
1590 }
1591
1592 #[cfg(feature = "devtools")]
1593 pub fn devtools(&self) -> Option<&strata_devtools::DevTools> {
1595 self.devtools.as_ref()
1596 }
1597
1598 #[cfg(feature = "devtools")]
1599 pub fn devtools_mut(&mut self) -> Option<&mut strata_devtools::DevTools> {
1601 self.devtools.as_mut()
1602 }
1603
1604 pub fn run_with_window<W, E, P>(
1606 &mut self,
1607 window: &mut W,
1608 event_loop: &mut E,
1609 compositor: &mut SwapchainCompositor,
1610 presenter: &mut P,
1611 ) where
1612 W: PlatformWindow,
1613 E: EventLoop,
1614 P: SurfacePresenter,
1615 {
1616 let _ = self.render_frame(compositor, presenter, true);
1618
1619 event_loop.run(|event, control| {
1620 match event {
1621 PlatformEvent::WindowResized { width, height } => {
1622 compositor.resize(width, height, self.dpr);
1623 let _ = presenter.resize(width, height);
1624 }
1625 PlatformEvent::ScaleFactorChanged { scale_factor } => {
1626 compositor.resize(
1627 self.viewport_width as u32,
1628 self.viewport_height as u32,
1629 scale_factor,
1630 );
1631 }
1632 PlatformEvent::WindowCloseRequested => {
1633 *control = EventLoopControl::Exit;
1634 return;
1635 }
1636 _ => {}
1637 }
1638
1639 let needs_redraw = self.step_event(&event);
1640 window.set_cursor(self.current_cursor());
1641
1642 if needs_redraw || window.is_redraw_requested() {
1643 let _ = self.render_frame(compositor, presenter, false);
1644 }
1645
1646 *control = EventLoopControl::Wait;
1648 });
1649 }
1650
1651 pub fn render_to_framebuffer(&mut self) -> strata_render::rasterizer::FrameBuffer {
1653 self.tick_frame();
1654 let width = (self.viewport_width * self.dpr).max(1.0).ceil() as usize;
1655 let height = (self.viewport_height * self.dpr).max(1.0).ceil() as usize;
1656 let mut fb = strata_render::rasterizer::FrameBuffer::new(width, height);
1657 fb.execute_display_list(&self.display_list);
1658 fb
1659 }
1660
1661 pub fn export_png<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), String> {
1663 let fb = self.render_to_framebuffer();
1664 fb.export_png(path).map_err(|e| e.to_string())
1665 }
1666
1667 #[cfg(feature = "devtools")]
1668 pub fn sync_to_devtools(&self, dispatcher: &strata_devtools::cdp::CdpDispatcher) {
1670 dispatcher.update_from_ir(
1671 &self.ir_graph,
1672 &self.base_node_styles,
1673 self.frame_count,
1674 self.layout_computations,
1675 );
1676 }
1677}