Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
use super::reconcile::BoxNodeWriter;
use super::scroll_state::NO_SCROLL_STATE_SLOT;
use super::*;
use crate::layout::node_data::{NodeFlag, NodeSlotId};
use crate::painting::paintable_data::*;
use crate::painting::paintable_geometry;
use crate::painting::paintable_rows::{PaintableRowsRead, PaintableRowsWrite};
use libgfx_rust::FloatPoint;
pub(crate) struct BoxBuildEnvironment<'a, Arena> {
pub layout_arena: &'a Arena,
pub pixel_ratio: f64,
}
pub(crate) trait AnchorScrollShiftResolver {
fn default_scroll_shift_anchor(&self, slot: NodeSlotId) -> NodeSlotId;
fn spatial_node_index(&self, slot: NodeSlotId) -> SpatialNodeIndex;
}
#[derive(Clone)]
pub(crate) struct PaintableVisualContextAssignment {
pub slot: NodeSlotId,
pub own_scroll_node_index: SpatialNodeIndex,
pub node_identity: i64,
pub has_accumulated_visual_context: bool,
pub accumulated_visual_context: ContextRef,
pub accumulated_visual_context_for_descendants: ContextRef,
pub has_non_invertible_css_transform: bool,
pub hidden_by_empty_svg_mask_or_clip: bool,
pub record: PaintableVisualContextRecord,
pub node_handles: BoxVisualContextNodeHandles,
/// The bounds of the SVG filter the box references, as the build gathered them, which the row takes as the
/// assignment applies. None for an assignment no build gathered.
pub gathered_svg_filter_bounds: Option<Option<crate::layout::used_values::FfiCssPixelRect>>,
}
impl PaintableVisualContextAssignment {
pub(crate) fn from_data(slot: NodeSlotId, data: &PaintableData, record: PaintableVisualContextRecord) -> Self {
Self {
slot,
own_scroll_node_index: data.own_scroll_node_index,
node_identity: data.node_identity,
has_accumulated_visual_context: data.has_accumulated_visual_context,
accumulated_visual_context: data.accumulated_visual_context,
accumulated_visual_context_for_descendants: data.accumulated_visual_context_for_descendants,
has_non_invertible_css_transform: data.has_flag(PaintableFlag::HasNonInvertibleCssTransform),
hidden_by_empty_svg_mask_or_clip: data.has_flag(PaintableFlag::HiddenByEmptySvgMaskOrClip),
record,
node_handles: BoxVisualContextNodeHandles::default(),
gathered_svg_filter_bounds: None,
}
}
pub(crate) fn apply(self, layout_arena: &mut impl PaintableRowsWrite) {
use crate::painting::record::change_ticks::RowPaintChange;
if let Some(svg_filter_bounds) = self.gathered_svg_filter_bounds {
super::node_values::set_svg_filter_bounds(layout_arena, self.slot, svg_filter_bounds);
}
// Commands and hit-test items name the row's own nodes; the scroll metadata of every
// descendant names the nearest scroll node above it.
let (scroll_nodes_changed, non_invertible_transform_flipped) = match layout_arena
.paintable_visual_context_record(self.slot)
{
Some(_) => {
let data = layout_arena.paintable_data(self.slot);
(
data.own_scroll_node_index != self.own_scroll_node_index
|| data.node_identity != self.node_identity,
data.has_flag(PaintableFlag::HasNonInvertibleCssTransform) != self.has_non_invertible_css_transform,
)
}
None => (false, false),
};
{
let mut data = layout_arena.paintable_data_mut(self.slot);
data.establishes_stacking_context = self.record.stacking_context.establishes_stacking_context;
data.own_scroll_node_index = self.own_scroll_node_index;
data.node_identity = self.node_identity;
data.has_accumulated_visual_context = self.has_accumulated_visual_context;
data.accumulated_visual_context = self.accumulated_visual_context;
data.accumulated_visual_context_for_descendants = self.accumulated_visual_context_for_descendants;
data.set_flag(
PaintableFlag::HasNonInvertibleCssTransform,
self.has_non_invertible_css_transform,
);
data.set_flag(
PaintableFlag::HiddenByEmptySvgMaskOrClip,
self.hidden_by_empty_svg_mask_or_clip,
);
}
layout_arena.set_paintable_visual_context_record(self.slot, self.record, self.node_handles);
if scroll_nodes_changed {
layout_arena.note_paint_change(self.slot, RowPaintChange::EVERYTHING_IT_PAINTS);
layout_arena.note_paint_change_in_paint_subtree(self.slot, RowPaintChange::SCROLL_METADATA);
}
if non_invertible_transform_flipped {
layout_arena.note_paint_change(self.slot, RowPaintChange::ORDER | RowPaintChange::EVERYTHING_IT_PAINTS);
}
}
}
// The scroll-like nodes that move content of the space of `index`, nearest first. A committed index
// can name a node an earlier box of this pass retired; the walk stops there, so such a box
// contributes no scroll shift instead of a stale lookup.
fn scroll_like_nodes_up_to_viewport(
sink: &impl VisualContextNodeSink,
index: SpatialNodeIndex,
) -> Vec<SpatialNodeIndex> {
let mut scroll_like_nodes = Vec::new();
let mut current = index;
while current != VISUAL_VIEWPORT_NODE_INDEX {
let node = sink.spatial_node_at(current);
if !node.data.is_live() {
break;
}
if node.data.is_scroll_like() {
scroll_like_nodes.push(current);
}
current = node.parent;
}
scroll_like_nodes
}
// https://drafts.csswg.org/css-anchor-position-1/#default-scroll-shift
// After layout has been performed for abspos, it is additionally shifted by the default scroll shift, as if
// affected by a transform (before any other transforms).
// NB: The shift is the scroll movement of the frames between the box's containing block and its default
// anchor box. When the anchor is itself an anchor-positioned box, its layout position does not include
// its own paint-time shift, so each chained anchor's shift is emitted as well, masked to the axes that
// every link below it compensates in. The visited set and depth cap guard against malformed anchor chains.
fn append_anchor_scroll_shift_nodes<Arena: PaintableRowsRead, Sink: VisualContextNodeSink>(
env: &BoxBuildEnvironment<'_, Arena>,
sink: &mut Sink,
resolver: &dyn AnchorScrollShiftResolver,
layout_node: NodeSlotId,
first_anchor_node: NodeSlotId,
mut own_state: ContextRef,
) -> ContextRef {
let own_spatial_node_before_shifts = own_state.spatial;
let spatial_node_index = |node: NodeSlotId| {
if node == layout_node {
own_spatial_node_before_shifts
} else {
resolver.spatial_node_index(node)
}
};
let mut box_node = layout_node;
let mut compensate_horizontal_scroll = true;
let mut compensate_vertical_scroll = true;
let mut visited: Vec<NodeSlotId> = Vec::new();
const MAX_ANCHOR_CHAIN_DEPTH: usize = 32;
let mut anchor_node = first_anchor_node;
while !box_node.is_invalid() && !visited.contains(&box_node) && visited.len() < MAX_ANCHOR_CHAIN_DEPTH {
if anchor_node.is_invalid() {
break;
}
if !env.layout_arena.paintable_row_is_populated(box_node)
|| !env.layout_arena.paintable_row_is_populated(anchor_node)
{
break;
}
visited.push(box_node);
let box_flags = env.layout_arena.node_flags_if_live(box_node);
compensate_horizontal_scroll =
compensate_horizontal_scroll && box_flags & NodeFlag::CompensatesForHorizontalScroll as u32 != 0;
compensate_vertical_scroll =
compensate_vertical_scroll && box_flags & NodeFlag::CompensatesForVerticalScroll as u32 != 0;
let anchor_scroll_chain = scroll_like_nodes_up_to_viewport(sink, spatial_node_index(anchor_node));
let base_scroll_chain = scroll_like_nodes_up_to_viewport(sink, spatial_node_index(box_node));
let shared_scroll_node = base_scroll_chain
.iter()
.copied()
.find(|node| anchor_scroll_chain.contains(node));
let below_shared_scroll_node = |chain: &[SpatialNodeIndex]| {
chain
.iter()
.copied()
.take_while(|node| Some(*node) != shared_scroll_node)
.collect::<Vec<_>>()
};
for scroll_node_index in below_shared_scroll_node(&anchor_scroll_chain) {
own_state = sink.append_spatial_node_under(
own_state,
SpatialData::AnchorScrollShift(AnchorScrollShift {
scroll_node_index,
negate: false,
compensate_horizontal_scroll,
compensate_vertical_scroll,
}),
);
}
for scroll_node_index in below_shared_scroll_node(&base_scroll_chain) {
own_state = sink.append_spatial_node_under(
own_state,
SpatialData::AnchorScrollShift(AnchorScrollShift {
scroll_node_index,
negate: true,
compensate_horizontal_scroll,
compensate_vertical_scroll,
}),
);
}
box_node = anchor_node;
anchor_node = resolver.default_scroll_shift_anchor(anchor_node);
}
own_state
}
// Positioned descendants skip intermediate overflow clips. Share the new clip when
// their spatial and clip chains coincide; otherwise append it under their own chain.
fn append_clip_to_positioned_chain<Sink: VisualContextNodeSink>(
sink: &mut Sink,
chain: PositioningContext,
normal_before: ContextRef,
normal_after: ContextRef,
data: ClipNodeData,
) -> PositioningContext {
let clip = if chain.spatial == normal_before.spatial && chain.clip == normal_before.clip {
normal_after.clip
} else {
sink.append_clip_node(data, chain.clip, chain.spatial)
};
PositioningContext { clip, ..chain }
}
pub(crate) fn build_box_visual_context_nodes<Arena: PaintableRowsRead>(
env: &BoxBuildEnvironment<'_, Arena>,
sink: &mut BoxNodeWriter<'_>,
slot: NodeSlotId,
inherited: DescendantVisualContexts,
anchor_scroll_shift_resolver: &dyn AnchorScrollShiftResolver,
) -> PaintableVisualContextAssignment {
let layout_arena = env.layout_arena;
let (facts, svg_filter_bounds) = super::build::BoxFacts::gather(layout_arena, slot, env.pixel_ratio, true);
let position = crate::painting::style_queries::position(layout_arena, slot);
let is_fixed = position == crate::css::css_enums::positioning::FIXED;
let is_absolute = position == crate::css::css_enums::positioning::ABSOLUTE;
let is_sticky = position == crate::css::css_enums::positioning::STICKY;
let layout_node = slot;
let stacking_context_facts = crate::painting::stacking_context::StackingContextFacts::gather(
layout_arena,
slot,
inherited.enclosing_stacking_context,
);
let mut assignment = PaintableVisualContextAssignment::from_data(
slot,
layout_arena.paintable_data(slot),
PaintableVisualContextRecord {
inherited_input: inherited,
output_for_descendants: inherited,
owns_geometry_dependent_nodes: false,
subtree_may_own_geometry_dependent_nodes: false,
stacking_context: stacking_context_facts,
},
);
assignment.own_scroll_node_index = VISUAL_VIEWPORT_NODE_INDEX;
assignment.node_identity = 0;
assignment.gathered_svg_filter_bounds = Some(svg_filter_bounds);
let inherited_chain = if is_fixed {
inherited.fixed_position
} else if is_absolute {
inherited.absolute_position
} else {
// In-flow and relatively positioned boxes inherit the normal descendant context from
// their visual parent.
inherited.normal
};
let mut nearest_scroll_like_node_for_descendants = inherited_chain.nearest_scroll_like_node;
// Build this element's own state from inherited state.
let mut own_state = inherited_chain.with_effect(inherited.effect);
own_state = append_anchor_scroll_shift_nodes(
env,
sink,
anchor_scroll_shift_resolver,
layout_node,
facts.default_scroll_shift_anchor,
own_state,
);
// Out-of-flow descendants can skip overflow and scroll clips from intermediate ancestors.
let establishes_absolute_cb = facts.establishes_absolute_containing_block;
let establishes_fixed_cb = facts.establishes_fixed_containing_block;
let mut state_for_absolute_position_descendants = inherited.absolute_position;
let mut state_for_fixed_position_descendants = inherited.fixed_position;
macro_rules! append_clip_to_own_and_positioned_descendant_contexts {
($make:expr) => {{
let normal_before = own_state;
own_state = sink.append_clip_node_under(own_state, $make);
let normal_after = own_state;
if !establishes_absolute_cb {
state_for_absolute_position_descendants = append_clip_to_positioned_chain(
sink,
state_for_absolute_position_descendants,
normal_before,
normal_after,
$make,
);
}
if !establishes_fixed_cb {
state_for_fixed_position_descendants = append_clip_to_positioned_chain(
sink,
state_for_fixed_position_descendants,
normal_before,
normal_after,
$make,
);
}
}};
}
// NB: Layout decides the clip in the parent's space, so the box's own sticky offset, effects and transform go
// under it.
if let Some(clip_decided_by_parent) = facts.clip_decided_by_parent {
append_clip_to_own_and_positioned_descendant_contexts!(ClipNodeData::Rect(clip_decided_by_parent));
}
macro_rules! append_shared_effect {
($make:expr) => {{
let effect = sink.append_effect_node($make, own_state.effect, own_state.spatial, own_state.clip);
own_state.effect = effect;
}};
}
if is_sticky {
// The scroll state fills in the geometry once the tree is built. The scroller is the nearest scroll node
// above any enclosing sticky boxes, as the scroll state resolves it.
let nearest_scroll_like_node = inherited_chain.nearest_scroll_like_node;
let (scroller, parent_sticky) = match &sink.spatial_node_at(nearest_scroll_like_node).data {
SpatialData::Sticky(parent) => (parent.scroller, Some(nearest_scroll_like_node)),
_ => (nearest_scroll_like_node, None),
};
own_state = sink.append_spatial_node_under(
own_state,
SpatialData::Sticky(StickyData::unconstrained(
scroller,
parent_sticky,
NO_SCROLL_STATE_SLOT,
slot,
)),
);
nearest_scroll_like_node_for_descendants = own_state.spatial;
}
let transform_data = facts.transform;
let effects_layer_is_inside_transform_and_clips = facts.effects_layer_is_inside_transform_and_clips();
if facts.effects.is_some() && !effects_layer_is_inside_transform_and_clips {
append_shared_effect!(EffectNodeData::Effects(facts.effects_data().unwrap()));
}
let flattens_inherited_transform = inherited.flattens_inherited_transform;
let mut appended_transform_node = false;
if let Some(mut transform) = transform_data {
transform.flattens_inherited_transform = flattens_inherited_transform;
transform.sorting_context_root_index = inherited.sorting_context_root;
transform.establishes_sorting_context =
facts.establishes_or_extends_3d_rendering_context && inherited.sorting_context_root.is_none();
assignment.has_non_invertible_css_transform = !facts.transform_is_invertible;
own_state = sink.append_spatial_node_under(own_state, SpatialData::Transform(transform));
appended_transform_node = true;
} else {
assignment.has_non_invertible_css_transform = false;
}
let inherited_plane_root = if is_fixed {
inherited.fixed_position.plane_root
} else if is_absolute {
inherited.absolute_position.plane_root
} else {
inherited.normal.plane_root
};
let establishes_or_extends_3d_rendering_context = facts.establishes_or_extends_3d_rendering_context;
let node_data_flags = layout_arena.node_flags_if_live(layout_node);
let invisible_to_3d_rendering_contexts = node_data_flags & NodeFlag::Anonymous as u32 != 0
&& !layout_arena.node_is_generated_for_pseudo_element(layout_node);
let mut appended_synthetic_plane = false;
if !invisible_to_3d_rendering_contexts && establishes_or_extends_3d_rendering_context && !appended_transform_node {
own_state = sink.append_spatial_node_under(
own_state,
SpatialData::Transform(TransformData {
matrix: libgfx_rust::FloatMatrix4x4::identity(),
origin: FloatPoint::default(),
sorting_context_root_index: inherited.sorting_context_root,
flattens_inherited_transform,
role: TransformDataRole::CssTransform,
synthetic_plane: true,
establishes_sorting_context: inherited.sorting_context_root.is_none(),
bounds: libgfx_rust::FloatRect::default(),
}),
);
appended_synthetic_plane = true;
}
let mut appended_backface_marker = false;
// https://drafts.csswg.org/css-transforms-2/#backface-visibility-property
// NB: Whether the element's backface is visible depends on its accumulated 3D transformation matrix, which
// is only known at replay time once scroll offsets have been applied. The node recorded below marks the
// content to skip and stores the plane root from which that matrix is accumulated. The plane root bounds
// the accumulation to the element's 3D rendering context.
// AD-HOC: The spec determines visibility from the sign of m33 in the accumulated matrix. That is wrong for
// matrices with a perspective component, so we test the z-component of the transformed plane normal
// instead. See: https://github.com/w3c/csswg-drafts/issues/917.
if facts.backface_hidden {
own_state = sink.append_spatial_node_under(
own_state,
SpatialData::BackfaceVisibility(BackfaceVisibilityData {
plane_root_index: inherited_plane_root,
flattens_inherited_transform: !appended_transform_node
&& !appended_synthetic_plane
&& flattens_inherited_transform,
}),
);
appended_backface_marker = true;
}
// https://drafts.csswg.org/css-transforms-2/#3d-rendering-contexts
// An element participates in a 3D rendering context if its parent establishes or extends a 3D rendering
// context. The position of each element in that three-dimensional space is determined by accumulating the
// transformation matrices up from the given element to the element that establishes the 3D rendering context.
// NB: Children of an element that neither establishes nor extends a 3D rendering context start a new plane
// below the element's own transform. Anonymous boxes carry no element style and are invisible to 3D
// rendering contexts, so they pass the inherited plane through unchanged. Pseudo-element boxes carry
// their own style and participate normally. An inherited flatten is only materialized by an appended
// node, so an element that appends none keeps it pending for its descendants.
let plane_root_for_descendants =
if establishes_or_extends_3d_rendering_context || invisible_to_3d_rendering_contexts {
inherited_plane_root
} else {
own_state.spatial
};
let inherited_flatten_still_pending = flattens_inherited_transform
&& !appended_transform_node
&& !appended_synthetic_plane
&& !appended_backface_marker;
let mut descendants_flatten_inherited_transform = if invisible_to_3d_rendering_contexts {
flattens_inherited_transform
} else {
!establishes_or_extends_3d_rendering_context || inherited_flatten_still_pending
};
// https://drafts.csswg.org/css-transforms-2/#3d-rendering-contexts
// A 3D rendering context is established by a transformable element whose used value for transform-style
// is preserve-3d and which itself is not part of a 3D rendering context. An element that establishes a
// 3D rendering context also participates in that context.
// NB: The establishing element's own state serves as the context's root; replay sorts the content
// recorded under it as the context's z=0 plane alongside the planes of the participants, whose
// transform nodes reference the root.
let mut sorting_context_root_for_descendants = inherited.sorting_context_root;
if !invisible_to_3d_rendering_contexts {
if !establishes_or_extends_3d_rendering_context {
sorting_context_root_for_descendants = None;
} else if sorting_context_root_for_descendants.is_none() {
sorting_context_root_for_descendants = Some(own_state.spatial);
}
}
if let Some(css_clip) = facts.css_clip {
append_clip_to_own_and_positioned_descendant_contexts!(ClipNodeData::Rect(css_clip));
}
if facts.clip_path.is_some() {
append_clip_to_own_and_positioned_descendant_contexts!(ClipNodeData::Path(facts.clip_path_data().unwrap()));
}
for mask_layer in &facts.mask_layers {
append_shared_effect!(EffectNodeData::Mask(*mask_layer));
}
assignment.hidden_by_empty_svg_mask_or_clip = facts.is_hidden_by_empty_svg_mask_or_clip();
// https://drafts.fxtf.org/filter-effects-2/#backdrop-filter-operation
// A backdrop filter is limited to the box's rounded border box in the box's own space, and a clip
// path clips the filtered backdrop along with the content, so its layer sits under the transform
// and clip nodes rather than above them. Masks apply to the filtered backdrop too, so the layer
// also sits under the box's masks, and replay draws the backdrop into the outermost mask's layer.
if effects_layer_is_inside_transform_and_clips {
append_shared_effect!(EffectNodeData::Effects(facts.effects_data().unwrap()));
}
if facts.needs_compositor_background_color_effect {
append_shared_effect!(EffectNodeData::BackgroundColorAnimation);
}
assignment.has_accumulated_visual_context = true;
assignment.accumulated_visual_context = own_state;
sink.begin_descendants();
// Build state for descendants: own state + perspective + clip + scroll.
let mut state_for_descendants = own_state;
if let Some(mut perspective) = facts.perspective {
perspective.flattens_inherited_transform = descendants_flatten_inherited_transform;
descendants_flatten_inherited_transform = false;
state_for_descendants =
sink.append_spatial_node_under(state_for_descendants, SpatialData::Perspective(perspective));
}
if facts.may_have_clip
&& let Some(overflow_clip) = facts.overflow_clip
{
state_for_descendants = sink.append_clip_node_under(state_for_descendants, ClipNodeData::Rect(overflow_clip));
if let Some(contour) = facts.overflow_clip_contour {
state_for_descendants = sink.append_clip_node_under(state_for_descendants, ClipNodeData::Path(contour));
}
}
if paintable_geometry::has_scrollable_overflow(layout_arena, slot)
|| crate::painting::chrome_geometry::keeps_scrolls_along_some_axis(layout_arena, slot)
{
state_for_descendants = sink.append_spatial_node_under(
state_for_descendants,
SpatialData::Scroll(ScrollData {
state_slot: NO_SCROLL_STATE_SLOT,
owner_paintable: slot,
}),
);
let scroll_node_index = state_for_descendants.spatial;
assignment.own_scroll_node_index = scroll_node_index;
assignment.node_identity = layout_arena.unique_node_ids().id(slot);
nearest_scroll_like_node_for_descendants = scroll_node_index;
}
// A snap area is identified across relayouts and processes by its element, like a scroll node.
if assignment.node_identity == 0
&& layout_arena
.node_style_if_live(slot)
.is_some_and(|style| style.has_scroll_snap_alignment())
{
assignment.node_identity = layout_arena.unique_node_ids().id(slot);
}
// Positioned descendants that escape into a viewport-establishing containing block lay
// out in the box's own coordinate space, not the viewport's user units, so they hang
// above the viewport transform node.
let state_for_positioned_descendants = PositioningContext {
spatial: state_for_descendants.spatial,
clip: state_for_descendants.clip,
nearest_scroll_like_node: nearest_scroll_like_node_for_descendants,
plane_root: plane_root_for_descendants,
};
if let Some(svg_viewport_transform) = super::build::svg_viewport_transform_of(layout_arena, slot) {
let mut viewport_transform_data = super::build::compute_svg_viewport_transform_data(
layout_arena,
slot,
svg_viewport_transform,
env.pixel_ratio,
);
viewport_transform_data.flattens_inherited_transform = descendants_flatten_inherited_transform;
descendants_flatten_inherited_transform = false;
state_for_descendants =
sink.append_spatial_node_under(state_for_descendants, SpatialData::Transform(viewport_transform_data));
}
assignment.accumulated_visual_context_for_descendants = state_for_descendants;
if establishes_absolute_cb {
state_for_absolute_position_descendants = state_for_positioned_descendants;
}
if establishes_fixed_cb {
state_for_fixed_position_descendants = state_for_positioned_descendants;
}
let descendant_contexts = DescendantVisualContexts {
effect: own_state.effect,
normal: PositioningContext {
spatial: state_for_descendants.spatial,
clip: state_for_descendants.clip,
nearest_scroll_like_node: nearest_scroll_like_node_for_descendants,
plane_root: plane_root_for_descendants,
},
absolute_position: state_for_absolute_position_descendants,
fixed_position: state_for_fixed_position_descendants,
flattens_inherited_transform: descendants_flatten_inherited_transform,
sorting_context_root: sorting_context_root_for_descendants,
enclosing_stacking_context: if stacking_context_facts.establishes_stacking_context {
slot
} else {
inherited.enclosing_stacking_context
},
};
assignment.record.output_for_descendants = descendant_contexts;
assignment
}