use strata_dom::{NodeBlueprint, Tag, View};
use strata_layout::prelude::*;
use strata_platform::{
EventLoop, EventLoopControl, LivePlatformWindow, NativeSurfaceWindow, PlatformEvent,
PlatformWindow, SoftwareSurfacePresenter, SwapchainCompositor, SwapchainFormat, WindowConfig,
};
use strata_render::compositor::DisplayList;
use strata_render::swapchain::{PresentError, SurfacePresenter};
use strata_style::types::{ComputedStyle, Dimension, Display, FlexDirection};
pub mod app;
pub mod edit;
pub mod launch;
pub mod platforms;
pub mod types;
mod a11y;
mod animation;
mod canvas3d;
pub mod dom_hydration;
mod events;
mod hit_test;
mod hover;
mod image;
mod input_hit_test;
mod layout_tree;
mod mcp;
mod profile;
mod scroll;
mod scrollbar;
mod selection;
pub mod spatial;
mod tailwind;
pub mod test_support;
pub use app::*;
pub use dom_hydration::*;
pub use edit::*;
pub(crate) use image::*;
pub use launch::*;
pub use platforms::*;
pub use profile::{FrameProfile, FrameProfileHook};
pub use spatial::*;
pub use test_support::{MatchMode, NodeQuery};
pub use types::*;
#[derive(Debug)]
pub struct AppRuntime {
pub root_blueprint: NodeBlueprint,
pub ir_graph: strata_dom::UiIrGraph,
pub layout_root: LayoutNode,
pub display_list: DisplayList,
pub spatial_index: SpatialIndex,
pub viewport_width: f32,
pub viewport_height: f32,
pub dpr: f32,
pub frame_count: u64,
pub active_focus: Option<ActiveInput>,
pub input_states: std::collections::HashMap<String, strata_dom::text_input::TextInputState>,
pub caret_blink_epoch: std::time::Instant,
pub last_caret_blink_state: bool,
pub current_cursor: strata_platform::window::CursorIcon,
pub drag_selection_active: bool,
pub last_click_info: Option<(std::time::Instant, f32, f32, usize)>,
pub pending_window_drag: Option<(f32, f32)>,
pub last_drag_click: Option<(std::time::Instant, f32, f32)>,
pub current_hover_path: Option<Vec<usize>>,
pub current_focus_path: Option<Vec<usize>>,
pub is_mouse_down: bool,
pub is_dark_mode: bool,
pub last_mouse_pos: (f32, f32),
pub hover_tooltip_text: Option<String>,
pub hover_tooltip_path: Option<Vec<usize>>,
pub hover_tooltip_anchor: (f32, f32),
pub hover_tooltip_since: Option<std::time::Instant>,
pub hover_tooltip_visible: bool,
pub hover_tooltip_delay: std::time::Duration,
pub hover_tooltip_style: strata_platform::HoverTooltipStyle,
pub scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
pub scroll_offsets_by_id: std::collections::HashMap<String, (f32, f32)>,
pub active_scrollbars: Vec<ActiveScrollbar>,
pub scrollbar_drag: Option<ScrollbarDrag>,
pub active_smooth_scroll: Option<SmoothScrollTracker>,
pub last_scroll_interaction: Option<std::time::Instant>,
pub applied_scroll_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
pub applied_portal_offsets: std::collections::HashMap<Vec<usize>, (f32, f32)>,
pub(crate) has_anchored_portals: bool,
pub runtime_start_epoch: std::time::Instant,
pub transition_manager: strata_style::transition::TransitionManager,
pub animation_manager: strata_style::animation::AnimationManager,
pub base_node_styles: std::collections::HashMap<u64, ComputedStyle>,
pub previous_node_styles: std::collections::HashMap<u64, ComputedStyle>,
pub node_paths: std::collections::HashMap<u64, Vec<usize>>,
pub path_node_ids: std::collections::HashMap<Vec<usize>, u64>,
pub view_transition_manager: crate::view_transition::ViewTransitionManager,
pub had_active_animations: bool,
pub gpu_path_pipeline: strata_render::GpuPathPipeline,
pub(crate) layout_computations: u64,
pub(crate) hover_paint_only: bool,
pub mcp_cursor: Option<strata_platform::McpCursorState>,
pub(crate) cursor_theme: std::sync::OnceLock<strata_platform::CursorTheme>,
pub a11y_bridge: strata_a11y::A11yBridge,
pub a11y_tree: Option<strata_a11y::A11yTree>,
pub a11y_updates_count: u64,
pub dynamic_text_bindings: Vec<DynamicTextBinding>,
pub dom_mutation_receiver: Option<std::sync::mpsc::Receiver<strata_js::DomMutationRecord>>,
#[cfg(feature = "devtools")]
pub devtools: Option<strata_devtools::DevTools>,
pub csd_controller: strata_platform::CsdController,
pub(crate) frame_profile: FrameProfile,
pub(crate) paint_dirty: bool,
pub(crate) viewport_3d_dirty: bool,
pub(crate) tracked_retained_3d: Vec<(strata_render::scene3d::RetainedScene3D, (u64, u64, u64))>,
pub(crate) compiles_skipped: u64,
pub(crate) frame_profile_hook: Option<FrameProfileHook>,
pub(crate) cached_stylesheets: Vec<std::sync::Arc<strata_style::StyleSheet>>,
pub pointer_capture_target: Option<(Vec<usize>, bool)>,
pub(crate) has_resize_listeners: bool,
pub observed_element_sizes: std::collections::HashMap<u64, (f32, f32)>,
pub(crate) last_pointer_pos: Option<(f32, f32)>,
pub(crate) pending_cursor_warp: Option<(f32, f32)>,
pub(crate) last_update_reconciled: bool,
pub(crate) active_dom_drag: Option<ActiveDomDrag>,
}
pub(crate) fn perf_logging_enabled() -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
}
pub(crate) fn perf_log_ms(label: &str, start: std::time::Instant, detail: impl std::fmt::Display) {
if perf_logging_enabled() {
eprintln!(
"[perf] {}: {:.3} ms ({})",
label,
start.elapsed().as_secs_f64() * 1000.0,
detail
);
}
}
pub(crate) fn perf_count_layout_nodes(node: &strata_layout::LayoutNode) -> usize {
let mut count = 0;
let mut stack = vec![node];
while let Some(n) = stack.pop() {
count += 1;
for child in &n.children {
stack.push(child);
}
}
count
}
pub(crate) fn perf_count_blueprint_nodes(node: &NodeBlueprint) -> usize {
let mut count = 0;
let mut stack = vec![node];
while let Some(n) = stack.pop() {
count += 1;
match n {
NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
for child in children {
stack.push(child);
}
}
NodeBlueprint::Text(_) | NodeBlueprint::DynamicText(_) | NodeBlueprint::Empty => {}
}
}
count
}
impl AppRuntime {
pub fn new(root_view: View, viewport_width: f32, viewport_height: f32, dpr: f32) -> Self {
#[cfg(target_os = "linux")]
strata_platform::init_pango_text_measurement();
let mut root_blueprint = root_view.root.flatten_fragments();
root_blueprint.ensure_entity_ids();
let mut ir_graph = Self::build_ir_graph(&root_blueprint);
let build_start = std::time::Instant::now();
let mut layout_root = Self::build_layout_tree(&root_blueprint);
if perf_logging_enabled() {
perf_log_ms(
"build_layout_tree_initial",
build_start,
format!("{} layout nodes", perf_count_layout_nodes(&layout_root)),
);
}
let compute_start = std::time::Instant::now();
layout_root.compute_layout(viewport_width, viewport_height);
Self::sync_layout_to_ir(&layout_root, &mut ir_graph);
let mut spatial_index = SpatialIndex::new();
spatial_index.rebuild(&root_blueprint, &layout_root);
if perf_logging_enabled() {
perf_log_ms(
"compute_layout_initial",
compute_start,
format!("{}x{}", viewport_width, viewport_height),
);
}
let mut dynamic_text_bindings = Vec::new();
let mut path_buf = Vec::new();
Self::collect_dynamic_text_bindings(
&root_blueprint,
&mut path_buf,
&mut dynamic_text_bindings,
);
let mut runtime = Self {
root_blueprint,
ir_graph,
layout_root,
display_list: DisplayList::new(),
spatial_index,
viewport_width,
viewport_height,
dpr,
frame_count: 0,
active_focus: None,
input_states: std::collections::HashMap::new(),
caret_blink_epoch: std::time::Instant::now(),
last_caret_blink_state: true,
current_cursor: strata_platform::window::CursorIcon::Default,
drag_selection_active: false,
last_click_info: None,
pending_window_drag: None,
last_drag_click: None,
current_hover_path: None,
current_focus_path: None,
is_mouse_down: false,
is_dark_mode: false,
last_mouse_pos: (0.0, 0.0),
hover_tooltip_text: None,
hover_tooltip_path: None,
hover_tooltip_anchor: (0.0, 0.0),
hover_tooltip_since: None,
hover_tooltip_visible: false,
hover_tooltip_delay: std::time::Duration::from_millis(450),
hover_tooltip_style: strata_platform::HoverTooltipStyle::default(),
scroll_offsets: std::collections::HashMap::new(),
scroll_offsets_by_id: std::collections::HashMap::new(),
active_scrollbars: Vec::new(),
scrollbar_drag: None,
active_smooth_scroll: None,
last_scroll_interaction: None,
applied_scroll_offsets: std::collections::HashMap::new(),
applied_portal_offsets: std::collections::HashMap::new(),
has_anchored_portals: false,
runtime_start_epoch: std::time::Instant::now(),
transition_manager: strata_style::transition::TransitionManager::new(),
animation_manager: strata_style::animation::AnimationManager::new(),
base_node_styles: std::collections::HashMap::new(),
previous_node_styles: std::collections::HashMap::new(),
node_paths: std::collections::HashMap::new(),
path_node_ids: std::collections::HashMap::new(),
view_transition_manager: crate::view_transition::ViewTransitionManager::new(),
had_active_animations: false,
gpu_path_pipeline: strata_render::GpuPathPipeline::new(viewport_width, viewport_height),
layout_computations: 1,
hover_paint_only: false,
mcp_cursor: None,
cursor_theme: std::sync::OnceLock::new(),
a11y_bridge: strata_a11y::A11yBridge::new(),
a11y_tree: None,
a11y_updates_count: 0,
dynamic_text_bindings,
dom_mutation_receiver: None,
#[cfg(feature = "devtools")]
devtools: None,
csd_controller: strata_platform::CsdController::default(),
frame_profile: FrameProfile::default(),
paint_dirty: true,
viewport_3d_dirty: false,
tracked_retained_3d: Vec::new(),
compiles_skipped: 0,
frame_profile_hook: None,
cached_stylesheets: Vec::new(),
pointer_capture_target: None,
has_resize_listeners: false,
observed_element_sizes: std::collections::HashMap::new(),
last_pointer_pos: None,
pending_cursor_warp: None,
last_update_reconciled: false,
active_dom_drag: None,
};
runtime.has_resize_listeners =
Self::blueprint_has_resize_listeners(&runtime.root_blueprint);
let initial_sheets = Self::collect_stylesheets_from_blueprint(&runtime.root_blueprint);
for sheet in &initial_sheets {
runtime.register_keyframes_stylesheet(sheet);
}
runtime.cached_stylesheets = initial_sheets;
runtime.sync_tree_animations(0.0);
runtime.apply_viewport_clamps();
runtime.apply_scroll_offsets();
runtime.dispatch_resize_observers();
runtime
.spatial_index
.rebuild(&runtime.root_blueprint, &runtime.layout_root);
runtime.update_accessibility_tree();
runtime.compile_display_list();
runtime
}
pub fn apply_window_config(&mut self, config: &WindowConfig) -> &mut Self {
self.hover_tooltip_delay = config.tooltip_delay;
self.hover_tooltip_style = config.tooltip_style;
if self.hover_tooltip_visible {
self.paint_dirty = true;
}
self
}
pub fn set_hover_tooltip_delay(&mut self, delay: std::time::Duration) -> &mut Self {
self.hover_tooltip_delay = delay;
self
}
pub fn set_hover_tooltip_delay_ms(&mut self, delay_ms: u64) -> &mut Self {
self.hover_tooltip_delay = std::time::Duration::from_millis(delay_ms);
self
}
pub fn hover_tooltip_delay(&self) -> std::time::Duration {
self.hover_tooltip_delay
}
pub fn set_hover_tooltip_style(
&mut self,
style: strata_platform::HoverTooltipStyle,
) -> &mut Self {
self.hover_tooltip_style = style;
if self.hover_tooltip_visible {
self.paint_dirty = true;
}
self
}
pub fn hover_tooltip_style(&self) -> strata_platform::HoverTooltipStyle {
self.hover_tooltip_style
}
pub fn tick_frame(&mut self) -> &DisplayList {
self.frame_count += 1;
self.unapply_scroll_offsets();
let compute_start = std::time::Instant::now();
self.layout_root
.compute_layout(self.viewport_width, self.viewport_height);
Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
self.layout_computations += 1;
self.frame_profile.layout += compute_start.elapsed();
if perf_logging_enabled() {
perf_log_ms(
"compute_layout_tick",
compute_start,
format!(
"{} layout nodes",
perf_count_layout_nodes(&self.layout_root)
),
);
}
self.apply_viewport_clamps();
self.apply_scroll_offsets();
self.dispatch_resize_observers();
self.spatial_index
.rebuild(&self.root_blueprint, &self.layout_root);
self.update_accessibility_tree();
self.compile_display_list();
&self.display_list
}
pub fn interaction_context(&self) -> InteractionContext<'_> {
InteractionContext {
hovered_path: self.current_hover_path.as_deref(),
focused_path: self.current_focus_path.as_deref(),
is_mouse_down: self.is_mouse_down,
is_dark_mode: self.is_dark_mode,
}
}
pub fn set_dark_mode(&mut self, is_dark: bool) -> bool {
if self.is_dark_mode != is_dark {
self.is_dark_mode = is_dark;
self.rebuild_layout_tree();
true
} else {
false
}
}
pub fn set_focus_path(&mut self, path: Option<Vec<usize>>) -> bool {
if self.current_focus_path != path {
self.current_focus_path = path;
self.rebuild_layout_tree();
true
} else {
false
}
}
pub fn rebuild_spatial_index(&mut self) {
self.spatial_index
.rebuild(&self.root_blueprint, &self.layout_root);
}
pub fn query_entity_at_point(&self, px: f32, py: f32) -> Option<strata_primitives::EntityId> {
self.spatial_index.query_entity_at_point(px, py)
}
pub fn query_event_at_point(
&self,
px: f32,
py: f32,
event_type: strata_dom::EventType,
) -> Option<(
strata_primitives::EntityId,
std::rc::Rc<dyn Fn(strata_dom::Event)>,
strata_layout::Rect,
)> {
self.spatial_index.query_event_at_point(px, py, event_type)
}
pub fn find_layout_by_entity(
&self,
entity_id: strata_primitives::EntityId,
) -> Option<&LayoutNode> {
self.layout_root.find_by_entity_id(entity_id)
}
pub fn find_layout_mut_by_entity(
&mut self,
entity_id: strata_primitives::EntityId,
) -> Option<&mut LayoutNode> {
self.layout_root.find_by_entity_id_mut(entity_id)
}
pub fn find_blueprint_by_entity(
&self,
entity_id: strata_primitives::EntityId,
) -> Option<&NodeBlueprint> {
self.root_blueprint.find_by_entity_id(entity_id)
}
pub fn query_element_rect(&self, element_id: &str) -> Option<strata_layout::Rect> {
fn find_rec(node: &LayoutNode, target_id: &str) -> Option<strata_layout::Rect> {
if node.element_id.as_deref() == Some(target_id) {
return Some(node.geometry.border_box);
}
for child in &node.children {
if let Some(rect) = find_rec(child, target_id) {
return Some(rect);
}
}
None
}
find_rec(&self.layout_root, element_id)
}
pub fn warp_cursor(&mut self, x: f32, y: f32) {
self.last_pointer_pos = Some((x, y));
self.pending_cursor_warp = Some((x, y));
#[cfg(target_os = "linux")]
strata_platform::gtk_warp_cursor(x as f64, y as f64);
}
pub fn set_cursor_position(&mut self, x: f32, y: f32) {
self.warp_cursor(x, y);
}
pub fn update_element_flex(
&mut self,
element_id: &str,
flex_grow: f32,
flex_shrink: f32,
flex_basis: Option<strata_style::types::Dimension>,
) -> bool {
fn update_rec(
node: &mut LayoutNode,
target_id: &str,
flex_grow: f32,
flex_shrink: f32,
flex_basis: Option<strata_style::types::Dimension>,
) -> bool {
if node.element_id.as_deref() == Some(target_id) {
node.style.flex_grow = flex_grow;
node.style.flex_shrink = flex_shrink;
if let Some(basis) = flex_basis {
node.style.flex_basis = basis;
}
node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
return true;
}
let mut changed = false;
for child in &mut node.children {
if update_rec(child, target_id, flex_grow, flex_shrink, flex_basis) {
changed = true;
}
}
if changed {
node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
}
changed
}
update_rec(
&mut self.layout_root,
element_id,
flex_grow,
flex_shrink,
flex_basis,
)
}
pub fn update_split_ratios(&mut self, updates: &[(&str, f32)]) -> bool {
let mut any_changed = false;
for &(id, ratio) in updates {
if self.update_element_flex(id, ratio, 1.0, None) {
any_changed = true;
}
}
if any_changed {
self.relayout_in_place();
}
any_changed
}
pub fn relayout_in_place(&mut self) {
self.unapply_scroll_offsets();
let compute_start = std::time::Instant::now();
self.layout_root
.compute_layout(self.viewport_width, self.viewport_height);
self.layout_computations += 1;
self.frame_profile.layout += compute_start.elapsed();
self.apply_viewport_clamps();
self.apply_scroll_offsets();
self.dispatch_resize_observers();
self.spatial_index
.rebuild(&self.root_blueprint, &self.layout_root);
self.paint_dirty = true;
self.compile_display_list();
}
pub(crate) fn blueprint_has_resize_listeners(bp: &NodeBlueprint) -> bool {
match bp {
NodeBlueprint::Element {
attributes,
children,
..
} => {
attributes.iter().any(|a| {
matches!(
a,
strata_dom::Attribute::EventListener {
event: strata_dom::EventType::Resize,
..
}
)
}) || children.iter().any(Self::blueprint_has_resize_listeners)
}
NodeBlueprint::Fragment(children) => {
children.iter().any(Self::blueprint_has_resize_listeners)
}
_ => false,
}
}
pub fn dispatch_resize_observers(&mut self) -> bool {
if !self.has_resize_listeners {
return false;
}
let mut pending: Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)> =
Vec::new();
let mut active_ids = std::collections::HashSet::new();
let mut path = Vec::new();
#[allow(clippy::too_many_arguments)]
fn collect_rec(
bp: &NodeBlueprint,
layout: &LayoutNode,
path: &mut Vec<usize>,
path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
observed: &mut std::collections::HashMap<u64, (f32, f32)>,
active_ids: &mut std::collections::HashSet<u64>,
pending: &mut Vec<(std::rc::Rc<dyn Fn(strata_dom::Event)>, strata_layout::Rect)>,
) {
if let NodeBlueprint::Element {
attributes,
children,
..
} = bp
{
let node_id = path_node_ids
.get(path)
.copied()
.unwrap_or_else(|| path_to_node_id(path));
let mut resize_handlers = Vec::new();
for attr in attributes {
if let strata_dom::Attribute::EventListener {
event: strata_dom::EventType::Resize,
handler,
} = attr
{
resize_handlers.push(handler.clone());
}
}
if !resize_handlers.is_empty() {
active_ids.insert(node_id);
let w = layout.geometry.border_box.width;
let h = layout.geometry.border_box.height;
let changed = match observed.get(&node_id) {
Some(&(pw, ph)) => (w - pw).abs() > 0.25 || (h - ph).abs() > 0.25,
None => true,
};
if changed {
observed.insert(node_id, (w, h));
for handler in resize_handlers {
pending.push((handler, layout.geometry.border_box));
}
}
}
for (idx, child_layout) in layout.children.iter().enumerate() {
if let Some(child_bp) = children.get(idx) {
path.push(idx);
collect_rec(
child_bp,
child_layout,
path,
path_node_ids,
observed,
active_ids,
pending,
);
path.pop();
}
}
}
}
collect_rec(
&self.root_blueprint,
&self.layout_root,
&mut path,
&self.path_node_ids,
&mut self.observed_element_sizes,
&mut active_ids,
&mut pending,
);
self.observed_element_sizes
.retain(|id, _| active_ids.contains(id));
if pending.is_empty() {
return false;
}
for (handler, rect) in pending {
let mut ev = strata_dom::Event::new(strata_dom::EventType::Resize);
ev.client_x = rect.x as f64;
ev.client_y = rect.y as f64;
ev.offset_x = rect.width as f64;
ev.offset_y = rect.height as f64;
ev.width = rect.width as f64;
ev.height = rect.height as f64;
handler(ev);
}
true
}
fn element_attr_value<'a>(
attrs: &'a [strata_dom::Attribute],
key_name: &str,
) -> Option<&'a str> {
attrs.iter().find_map(|a| match a {
strata_dom::Attribute::Property { key, value } if key == key_name => {
Some(value.as_str())
}
_ => None,
})
}
fn attributes_visually_equal(a: &[strata_dom::Attribute], b: &[strata_dom::Attribute]) -> bool {
let mut iter_a = a.iter().filter(|attr| {
!matches!(
attr,
strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
)
});
let mut iter_b = b.iter().filter(|attr| {
!matches!(
attr,
strata_dom::Attribute::EventListener { .. } | strata_dom::Attribute::Entity(_)
)
});
loop {
match (iter_a.next(), iter_b.next()) {
(None, None) => return true,
(Some(x), Some(y)) => match (x, y) {
(
strata_dom::Attribute::Property { key: k1, value: v1 },
strata_dom::Attribute::Property { key: k2, value: v2 },
) if k1 == k2 && v1 == v2 => {}
(
strata_dom::Attribute::DirectStyle(d1),
strata_dom::Attribute::DirectStyle(d2),
) if std::rc::Rc::ptr_eq(d1, d2) => {}
(
strata_dom::Attribute::ScenePayload(s1),
strata_dom::Attribute::ScenePayload(s2),
) if std::sync::Arc::ptr_eq(s1, s2) => {}
_ => return false,
},
_ => return false,
}
}
}
fn inherited_style_equal(
a: &strata_style::ComputedStyle,
b: &strata_style::ComputedStyle,
) -> bool {
a.color == b.color
&& a.font_family == b.font_family
&& a.font_size == b.font_size
&& a.root_font_size == b.root_font_size
&& a.font_weight == b.font_weight
&& a.font_style == b.font_style
&& a.text_align == b.text_align
&& a.line_height == b.line_height
&& a.letter_spacing == b.letter_spacing
&& a.text_decoration == b.text_decoration
&& a.text_transform == b.text_transform
&& a.text_overflow == b.text_overflow
&& a.white_space == b.white_space
&& a.cursor == b.cursor
&& a.user_select == b.user_select
&& a.pointer_events == b.pointer_events
&& a.visibility == b.visibility
&& a.caret_color == b.caret_color
&& a.border_collapse == b.border_collapse
&& a.border_spacing == b.border_spacing
&& a.caption_side == b.caption_side
&& a.custom_properties == b.custom_properties
}
fn blueprint_visually_equal(a: &NodeBlueprint, b: &NodeBlueprint) -> bool {
match (a, b) {
(NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => t1 == t2,
(NodeBlueprint::Empty, NodeBlueprint::Empty) => true,
(
NodeBlueprint::Element {
tag: t1,
classes: cls1,
attributes: a1,
children: c1,
},
NodeBlueprint::Element {
tag: t2,
classes: cls2,
attributes: a2,
children: c2,
},
) => {
t1 == t2
&& cls1 == cls2
&& c1.len() == c2.len()
&& Self::attributes_visually_equal(a1, a2)
&& c1
.iter()
.zip(c2.iter())
.all(|(x, y)| Self::blueprint_visually_equal(x, y))
}
_ => false,
}
}
fn reconcile_layout_subtree(
old_bp: &NodeBlueprint,
new_bp: &NodeBlueprint,
layout_node: &mut LayoutNode,
parent_style: Option<&strata_style::ComputedStyle>,
parent_inherited_changed: bool,
stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
ctx: &crate::runtime::InteractionContext,
) -> Option<bool> {
match (old_bp, new_bp) {
(NodeBlueprint::Text(t1), NodeBlueprint::Text(t2)) => {
if t1 == t2 && !parent_inherited_changed {
Some(false)
} else {
*layout_node = Self::build_text_leaf_layout_node(t2.clone(), parent_style);
Some(true)
}
}
(
NodeBlueprint::Element { tag: t1, .. },
NodeBlueprint::Element { tag: t2, .. },
) if t1 == t2
&& matches!(
t1,
strata_dom::Tag::Svg
| strata_dom::Tag::Path
| strata_dom::Tag::Input
| strata_dom::Tag::Img
) =>
{
if !parent_inherited_changed && Self::blueprint_visually_equal(old_bp, new_bp) {
if let Some(eid) = new_bp.entity_id() {
layout_node.entity_id = eid;
}
Some(false)
} else {
None
}
}
(
NodeBlueprint::Element {
tag: t1,
classes: cls1,
attributes: a1,
children: c1,
},
NodeBlueprint::Element {
tag: t2,
classes: cls2,
attributes: a2,
children: c2,
},
) if t1 == t2
&& !layout_node.is_top_layer
&& layout_node.children.len() == c1.len()
&& Self::element_attr_value(a1, "key") == Self::element_attr_value(a2, "key")
&& Self::element_attr_value(a1, "id") == Self::element_attr_value(a2, "id") =>
{
let self_props_changed = cls1 != cls2 || !Self::attributes_visually_equal(a1, a2);
let single_text_changed = c1.len() == 1
&& c2.len() == 1
&& matches!(
(&c1[0], &c2[0]),
(NodeBlueprint::Text(x), NodeBlueprint::Text(y)) if x != y
);
let (self_rewritten, child_inherited_changed) =
if self_props_changed || parent_inherited_changed || single_text_changed {
let shallow_bp = NodeBlueprint::Element {
tag: *t2,
classes: cls2.clone(),
attributes: a2.clone(),
children: Vec::new(),
};
let mut path_buf = Vec::new();
let mut ancestors = Vec::new();
let mut updated = Self::build_layout_tree_full(
&shallow_bp,
parent_style,
&mut path_buf,
ctx,
stylesheets,
&mut ancestors,
&[],
true,
(false, false, false),
);
Self::apply_single_text_inline_intrinsic_sizing(&mut updated.style, c2);
if let Some(eid) = new_bp.entity_id() {
updated.entity_id = eid;
}
let inh_changed =
!Self::inherited_style_equal(&layout_node.style, &updated.style);
updated.children = std::mem::take(&mut layout_node.children);
*layout_node = updated;
(true, inh_changed)
} else {
if let Some(eid) = new_bp.entity_id() {
layout_node.entity_id = eid;
}
(false, false)
};
let parent_style_for_children = layout_node.style.clone();
let mut children_changed = c1.len() != c2.len();
let common = c1.len().min(c2.len());
for i in 0..common {
match Self::reconcile_layout_subtree(
&c1[i],
&c2[i],
&mut layout_node.children[i],
Some(&parent_style_for_children),
child_inherited_changed,
stylesheets,
ctx,
) {
Some(false) => {}
Some(true) => children_changed = true,
None => {
let mut path_buf = Vec::new();
let mut ancestors = Vec::new();
layout_node.children[i] = Self::build_layout_tree_full(
&c2[i],
Some(&parent_style_for_children),
&mut path_buf,
ctx,
stylesheets,
&mut ancestors,
&[],
i + 1 == c2.len(),
(false, false, false),
);
children_changed = true;
}
}
}
if c2.len() < c1.len() {
layout_node.children.truncate(c2.len());
} else if c2.len() > c1.len() {
for (offset, nc) in c2[common..].iter().enumerate() {
let idx = common + offset;
let mut path_buf = Vec::new();
let mut ancestors = Vec::new();
layout_node.children.push(Self::build_layout_tree_full(
nc,
Some(&parent_style_for_children),
&mut path_buf,
ctx,
stylesheets,
&mut ancestors,
&[],
idx + 1 == c2.len(),
(false, false, false),
));
}
}
if self_rewritten || children_changed {
layout_node.inline_items.clear();
layout_node.line_boxes.clear();
layout_node.layout_cache = strata_layout::tree::LayoutCacheEntry::invalid();
Some(true)
} else {
Some(false)
}
}
_ => None,
}
}
pub fn update_view(&mut self, new_view: View) {
self.unapply_scroll_offsets();
self.applied_scroll_offsets.clear();
self.applied_portal_offsets.clear();
let mut next_blueprint = new_view.root.flatten_fragments();
next_blueprint.ensure_entity_ids();
let old_blueprint = std::mem::replace(&mut self.root_blueprint, next_blueprint);
self.has_resize_listeners = Self::blueprint_has_resize_listeners(&self.root_blueprint);
self.ir_graph = Self::build_ir_graph(&self.root_blueprint);
let sheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
let sheets_unchanged = self.cached_stylesheets == sheets;
if !sheets_unchanged {
for sheet in &sheets {
self.register_keyframes_stylesheet(sheet);
}
self.cached_stylesheets = sheets;
}
let build_start = std::time::Instant::now();
let hover_safe = self.hover_is_paint_only()
|| self.current_hover_path.as_deref().is_none_or(|p| {
!Self::node_path_has_hover_effects_with_sheets(
&old_blueprint,
p,
&self.cached_stylesheets,
) && !Self::node_path_has_hover_effects_with_sheets(
&self.root_blueprint,
p,
&self.cached_stylesheets,
)
});
let reconciled = if self.cached_stylesheets.is_empty()
&& sheets_unchanged
&& hover_safe
&& self.current_focus_path.is_none()
{
let ctx = crate::runtime::InteractionContext {
hovered_path: None,
focused_path: None,
is_mouse_down: self.is_mouse_down,
is_dark_mode: self.is_dark_mode,
};
Self::reconcile_layout_subtree(
&old_blueprint,
&self.root_blueprint,
&mut self.layout_root,
None,
false,
&self.cached_stylesheets,
&ctx,
)
.is_some()
} else {
false
};
if !reconciled {
let ctx = self.interaction_context();
self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
}
self.last_update_reconciled = reconciled;
if perf_logging_enabled() {
perf_log_ms(
"build_layout_tree_update",
build_start,
format!(
"{} blueprint nodes -> {} layout nodes (reconciled={})",
perf_count_blueprint_nodes(&self.root_blueprint),
perf_count_layout_nodes(&self.layout_root),
reconciled
),
);
}
self.sync_active_input_layout();
self.dynamic_text_bindings.clear();
let mut path_buf = Vec::new();
Self::collect_dynamic_text_bindings(
&self.root_blueprint,
&mut path_buf,
&mut self.dynamic_text_bindings,
);
let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
let sync_start = std::time::Instant::now();
self.sync_tree_animations(now_ms);
if perf_logging_enabled() {
perf_log_ms("sync_tree_animations", sync_start, "update_view");
}
self.refresh_hover_tooltip_after_view_update();
self.tick_frame();
}
pub fn sync_dynamic_text(&mut self) -> bool {
if self.dynamic_text_bindings.is_empty() {
return false;
}
let mut changed = false;
for binding in &mut self.dynamic_text_bindings {
let new_text = (binding.closure)();
if new_text != binding.last_value {
binding.last_value = new_text.clone();
if let Some(node) = Self::find_layout_node_mut(&mut self.layout_root, &binding.path)
{
let is_mono = strata_layout::is_monospace_family(node.style.font_family);
let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
&new_text,
node.style.font_size,
node.style.line_height,
None,
is_mono,
node.style.font_family,
node.style.font_weight,
node.style.font_style,
);
node.style.width = strata_style::types::Dimension::Px(w);
node.style.height = strata_style::types::Dimension::Px(h);
node.geometry.content_box.width = w;
node.geometry.content_box.height = h;
node.text = Some(new_text);
node.layout_cache.is_valid = false;
changed = true;
}
}
}
if changed {
self.tick_frame();
true
} else {
false
}
}
pub fn cursor_theme(&self) -> &strata_platform::CursorTheme {
self.cursor_theme
.get_or_init(strata_platform::CursorTheme::load_active)
}
pub fn mark_viewport_3d_dirty(&mut self) {
self.viewport_3d_dirty = true;
}
pub fn poll_retained_3d_dirty(&self) -> bool {
if self.viewport_3d_dirty {
return true;
}
self.tracked_retained_3d
.iter()
.any(|(handle, last_gens)| handle.generations() != *last_gens)
}
pub fn acknowledge_retained_3d_presented(&mut self) {
self.viewport_3d_dirty = false;
for (handle, last_gens) in &mut self.tracked_retained_3d {
*last_gens = handle.generations();
}
}
pub fn has_uncapped_canvas3d(&self) -> bool {
fn walk(node: &NodeBlueprint) -> bool {
if let NodeBlueprint::Element {
attributes,
children,
..
} = node
{
if attributes.iter().any(|a| {
matches!(
a,
strata_dom::Attribute::Property { key, value }
if key == "data-strata-uncapped" && value == "true"
)
}) {
return true;
}
if children.iter().any(walk) {
return true;
}
}
false
}
walk(&self.root_blueprint)
}
pub fn mark_paint_dirty(&mut self) {
self.paint_dirty = true;
}
pub fn is_paint_dirty(&self) -> bool {
self.paint_dirty
}
pub fn compiles_skipped(&self) -> u64 {
self.compiles_skipped
}
pub fn compile_display_list_if_dirty(&mut self) -> bool {
if !self.paint_dirty {
self.compiles_skipped += 1;
return false;
}
self.compile_display_list();
true
}
pub fn compile_display_list(&mut self) {
let compile_start = std::time::Instant::now();
let viewport = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
Some(strata_layout::Rect::new(
0.0,
0.0,
self.viewport_width,
self.viewport_height,
))
} else {
None
};
self.display_list = strata_render::compositor::Compositor::build_display_list_with_viewport(
&self.layout_root,
viewport,
);
self.tracked_retained_3d.clear();
for cmd in &self.display_list.commands {
if let strata_render::compositor::DrawCommand::DrawViewport3D { scene, .. } = cmd {
if let Some(handle) = scene.retained_handle() {
self.tracked_retained_3d
.push((handle.clone(), handle.generations()));
}
}
}
self.render_scrollbars();
self.render_active_input_caret();
self.render_hover_tooltip();
self.gpu_path_pipeline
.resize(self.viewport_width, self.viewport_height);
self.gpu_path_pipeline
.compile_frame(&self.display_list, None);
self.frame_profile.compile += compile_start.elapsed();
self.paint_dirty = false;
static COMPILE_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let frame = COMPILE_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if frame < 6 || frame.is_multiple_of(120) {
perf_log_ms(
"compile_display_list",
compile_start,
format!(
"frame {} {}x{} {} commands",
frame,
self.viewport_width,
self.viewport_height,
self.display_list.commands.len()
),
);
}
}
#[inline]
pub fn gpu_path_segments(&self) -> &[strata_render::gpu_path::GpuPathSegment] {
&self.gpu_path_pipeline.batch.segments
}
#[inline]
pub fn gpu_path_uniform_bytes(&self) -> &[u8] {
self.gpu_path_pipeline.uniform_bytes()
}
pub fn step_event(&mut self, event: &PlatformEvent) -> bool {
#[cfg(feature = "devtools")]
if let Some(ref mut dt) = self.devtools {
if strata_devtools::DevToolsEventInterceptor::intercept(&mut dt.hud, event) {
return true;
}
}
let mut needs_redraw = match event {
PlatformEvent::WindowResized { width, height } => {
self.viewport_width = *width as f32;
self.viewport_height = *height as f32;
#[cfg(feature = "devtools")]
if let Some(ref mut dt) = self.devtools {
dt.hud
.update_bounds(self.viewport_width, self.viewport_height);
}
self.tick_frame();
true
}
PlatformEvent::ScaleFactorChanged { scale_factor } => {
self.dpr = *scale_factor;
self.tick_frame();
true
}
PlatformEvent::WindowFocused(_) => false,
PlatformEvent::WindowCloseRequested => false,
PlatformEvent::Scroll {
delta_x, delta_y, ..
} => {
let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
let (wheel_handled, scroll_changed) = self.dispatch_smooth_scroll_action(
self.last_mouse_pos.0,
self.last_mouse_pos.1,
*delta_x,
*delta_y,
);
if wheel_handled {
self.rebuild_layout_tree();
true
} else {
scroll_changed || tooltip_dismissed
}
}
PlatformEvent::AnimationTick => {
let scroll_changed = self.poll_smooth_scroll();
let anim_changed = self.poll_animations();
let caret_changed = self.poll_caret_blink();
let tooltip_changed = self.poll_hover_tooltip();
scroll_changed || anim_changed || caret_changed || tooltip_changed
}
PlatformEvent::MouseMove { x, y } => {
self.last_mouse_pos = (*x, *y);
let cur = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, *x, *y);
self.current_cursor = cur;
let hover_changed = self.update_hover(*x, *y);
self.dispatch_pointer_move_action(*x, *y).needs_redraw() || hover_changed
}
PlatformEvent::MouseDown { button, x, y } => {
let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
let btn_idx = button.to_button_index();
if *button == strata_platform::MouseButton::Left {
self.is_mouse_down = true;
}
let action = self.dispatch_pointer_down_action_with_button_and_modifiers(
*x,
*y,
btn_idx,
Default::default(),
);
let click_invoked = if *button != strata_platform::MouseButton::Right {
self.dispatch_mouse_click(*x, *y, btn_idx, 1)
} else {
self.dispatch_context_menu(*x, *y)
};
let dynamic_updated = self.sync_dynamic_text();
if action.needs_rebuild() || click_invoked || dynamic_updated {
self.rebuild_layout_tree();
true
} else {
tooltip_dismissed || action.needs_redraw() || self.restyle_for_active_change()
}
}
PlatformEvent::MouseUp { button, x, y } => {
let btn_idx = button.to_button_index();
let was_mouse_down = self.is_mouse_down;
if *button == strata_platform::MouseButton::Left {
self.is_mouse_down = false;
}
let action = self.dispatch_pointer_up_action_with_button(*x, *y, btn_idx);
if action.needs_rebuild() {
self.rebuild_layout_tree();
true
} else if was_mouse_down {
action.needs_redraw() || self.restyle_for_active_change()
} else {
action.needs_redraw()
}
}
PlatformEvent::CursorLeft => {
self.is_mouse_down = false;
self.current_cursor = strata_platform::window::CursorIcon::Default;
self.clear_hover()
}
PlatformEvent::KeyDown { .. }
| PlatformEvent::KeyUp { .. }
| PlatformEvent::ReceivedCharacter(_)
| PlatformEvent::ImePreedit { .. }
| PlatformEvent::ImeCommit(_) => {
let tooltip_dismissed = matches!(event, PlatformEvent::KeyDown { .. })
&& self.dismiss_hover_tooltip_and_repaint();
let res = self.dispatch_key_event(event);
let dynamic_updated = self.sync_dynamic_text();
tooltip_dismissed || res.needs_redraw() || dynamic_updated
}
PlatformEvent::FileDrop(paths) => {
let tooltip_dismissed = self.dismiss_hover_tooltip_and_repaint();
let drop_handled = self.dispatch_file_drop(paths.clone());
let dynamic_updated = self.sync_dynamic_text();
if drop_handled || dynamic_updated {
self.rebuild_layout_tree();
true
} else {
tooltip_dismissed
}
}
_ => false,
};
if self.poll_dom_mutations(None) {
needs_redraw = true;
}
if needs_redraw {
self.paint_dirty = true;
}
needs_redraw
}
pub fn layout_computations(&self) -> u64 {
self.layout_computations
}
pub fn last_update_reconciled(&self) -> bool {
self.last_update_reconciled
}
pub fn frame_profile(&self) -> FrameProfile {
self.frame_profile
}
pub fn set_frame_profile_hook(&mut self, hook: Option<Box<dyn FnMut(&FrameProfile)>>) {
self.frame_profile_hook = hook.map(FrameProfileHook);
}
pub fn record_raster_time(&mut self, elapsed: std::time::Duration) {
self.frame_profile.raster += elapsed;
}
pub fn record_present_time(&mut self, elapsed: std::time::Duration) {
self.frame_profile.present += elapsed;
}
pub fn finish_frame_profile(&mut self) -> FrameProfile {
let done = std::mem::take(&mut self.frame_profile);
if let Some(hook) = self.frame_profile_hook.as_mut() {
(hook.0)(&done);
}
done
}
pub fn render_frame<P: SurfacePresenter>(
&mut self,
compositor: &mut SwapchainCompositor,
presenter: &mut P,
force_redraw: bool,
) -> Result<bool, PresentError> {
#[cfg(feature = "devtools")]
let frame_start = std::time::Instant::now();
let retained_3d_dirty = self.poll_retained_3d_dirty();
if self.paint_dirty || self.frame_count == 0 || force_redraw {
self.tick_frame();
} else {
self.compiles_skipped += 1;
}
#[cfg(feature = "devtools")]
if let Some(ref mut dt) = self.devtools {
if dt.hud.state.is_visible {
dt.hud
.render_overlay(Some(&dt.profiler), &mut self.display_list);
}
}
#[cfg(feature = "devtools")]
let submit_start = std::time::Instant::now();
let present_start = std::time::Instant::now();
let res = compositor.render_and_present(
&self.display_list,
presenter,
force_redraw || retained_3d_dirty,
);
self.acknowledge_retained_3d_presented();
self.frame_profile.present += present_start.elapsed();
self.finish_frame_profile();
#[cfg(feature = "devtools")]
if let Some(ref mut dt) = self.devtools {
let submit_dur = submit_start.elapsed().as_micros() as u32;
let total_dur = frame_start.elapsed().as_micros() as u32;
let sample = strata_devtools::FrameTimingSample {
frame_index: self.frame_count,
vsync_wait_us: 0,
input_dispatch_us: 100,
signal_drain_us: 150,
parallel_reconcile_us: 200,
style_cascade_us: 250,
layout_solve_us: 300,
display_list_build_us: 350,
gpu_submit_us: submit_dur,
gpu_raster_duration_us: submit_dur.max(500),
total_cpu_frame_us: total_dur,
frame_budget_us: 16666,
layout_shift_score: 0.0,
};
dt.profiler.record_sample(sample);
dt.cdp_dispatcher.update_from_ir(
&self.ir_graph,
&self.base_node_styles,
self.frame_count,
self.layout_computations,
);
}
res
}
#[cfg(feature = "devtools")]
pub fn enable_devtools(&mut self) -> &mut strata_devtools::DevTools {
if self.devtools.is_none() {
let mut dt = strata_devtools::DevTools::new();
dt.hud
.update_bounds(self.viewport_width, self.viewport_height);
self.devtools = Some(dt);
}
self.devtools.as_mut().unwrap()
}
#[cfg(feature = "devtools")]
pub fn devtools(&self) -> Option<&strata_devtools::DevTools> {
self.devtools.as_ref()
}
#[cfg(feature = "devtools")]
pub fn devtools_mut(&mut self) -> Option<&mut strata_devtools::DevTools> {
self.devtools.as_mut()
}
pub fn run_with_window<W, E, P>(
&mut self,
window: &mut W,
event_loop: &mut E,
compositor: &mut SwapchainCompositor,
presenter: &mut P,
) where
W: PlatformWindow,
E: EventLoop,
P: SurfacePresenter,
{
let _ = self.render_frame(compositor, presenter, true);
event_loop.run(|event, control| {
match event {
PlatformEvent::WindowResized { width, height } => {
compositor.resize(width, height, self.dpr);
let _ = presenter.resize(width, height);
}
PlatformEvent::ScaleFactorChanged { scale_factor } => {
compositor.resize(
self.viewport_width as u32,
self.viewport_height as u32,
scale_factor,
);
}
PlatformEvent::WindowCloseRequested => {
*control = EventLoopControl::Exit;
return;
}
_ => {}
}
let needs_redraw = self.step_event(&event);
window.set_cursor(self.current_cursor());
if needs_redraw || window.is_redraw_requested() {
let _ = self.render_frame(compositor, presenter, false);
}
*control = EventLoopControl::Wait;
});
}
pub fn render_to_framebuffer(&mut self) -> strata_render::rasterizer::FrameBuffer {
self.tick_frame();
let width = (self.viewport_width * self.dpr).max(1.0).ceil() as usize;
let height = (self.viewport_height * self.dpr).max(1.0).ceil() as usize;
let mut fb = strata_render::rasterizer::FrameBuffer::new(width, height);
fb.execute_display_list(&self.display_list);
fb
}
pub fn export_png<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), String> {
let fb = self.render_to_framebuffer();
fb.export_png(path).map_err(|e| e.to_string())
}
#[cfg(feature = "devtools")]
pub fn sync_to_devtools(&self, dispatcher: &strata_devtools::cdp::CdpDispatcher) {
dispatcher.update_from_ir(
&self.ir_graph,
&self.base_node_styles,
self.frame_count,
self.layout_computations,
);
}
}