Skip to content

Truly independent web browser

39.9 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

use super::box_build::{
    AnchorScrollShiftResolver, BoxBuildEnvironment, PaintableVisualContextAssignment, build_box_visual_context_nodes,
};
use super::delta::VisualContextTreeDelta;
use super::dirty::{BoxDirtyBits, VisualContextBoxDirtyKind, VisualContextDirtySet, VisualContextUpdateScope};
use super::reconcile::BoxNodeWriter;
use super::refresh::compute_sticky_data;
use super::scroll_state::ScrollState;
use super::*;
use crate::fast_hash::{FastMap as HashMap, FastSet as HashSet};
use crate::layout::node_data::{NodeKind, NodeSlotId};
use crate::painting::host::FfiVisualContextTreeInputs;
use crate::painting::paint_order;
use crate::painting::paintable_rows::{PaintableRowsRead, PaintableRowsWrite};
use crate::painting::record::change_ticks::RowPaintChange;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct ChildCascade {
    input_changed: bool,
    geometry_walk: bool,
}

impl ChildCascade {
    fn visits_every_child(self) -> bool {
        self.input_changed || self.geometry_walk
    }
}

pub(crate) struct IncrementalUpdateOutcome {
    pub delta: VisualContextTreeDelta,
    pub assignments: Vec<PaintableVisualContextAssignment>,
}

pub(crate) enum IncrementalUpdateResult {
    Applied(Box<IncrementalUpdateOutcome>),
    NeedsFullBuild(VisualContextUpdateScope),
}

fn incremental_tree_requires_fresh_build(tree: &VisualContextTree, delta: &VisualContextTreeDelta) -> bool {
    delta.tombstoned_any_node && !tree.node_references_are_consistent()
}

/// Whether `slot` is inside the subtree of an SVG resource, where `known_to_be_outside` holds the boxes an earlier
/// call found outside of every one.
fn box_is_inside_svg_resource_subtree(
    layout_arena: &impl PaintableRowsRead,
    slot: NodeSlotId,
    known_to_be_outside: &mut HashSet<NodeSlotId>,
) -> bool {
    let mut node = Some(slot);
    while let Some(current) = node {
        if known_to_be_outside.contains(&current) {
            break;
        }
        if matches!(
            layout_arena.node_kind_if_live(current),
            Some(NodeKind::SVGMaskBox | NodeKind::SVGClipBox | NodeKind::SVGPatternBox)
        ) {
            return true;
        }
        node = layout_arena.node_parent_if_live(current);
    }
    // NB: Every box from `slot` up to where the walk ended is outside too, so a walk from a box below any of them
    //     ends there.
    let end = node;
    let mut node = Some(slot);
    while node != end
        && let Some(current) = node
    {
        known_to_be_outside.insert(current);
        node = layout_arena.node_parent_if_live(current);
    }
    false
}

#[derive(Default)]
struct WorkPlan {
    work: HashMap<NodeSlotId, BoxDirtyBits>,
    revalidate_children_of: HashSet<NodeSlotId>,
    ancestors_of_work: HashSet<NodeSlotId>,
}

fn expand_dirty_entries(
    layout_arena: &impl PaintableRowsRead,
    dirty: &VisualContextDirtySet,
    offset_path_boxes: &crate::cow_map::CowSet<NodeSlotId>,
) -> Result<WorkPlan, VisualContextUpdateScope> {
    let mut work: HashMap<NodeSlotId, BoxDirtyBits> = HashMap::default();
    let mut known_to_be_outside_svg_resources = HashSet::default();
    for (slot, bits) in dirty.boxes.iter() {
        if !layout_arena.paintable_row_is_populated(*slot) {
            continue;
        }
        if box_is_inside_svg_resource_subtree(layout_arena, *slot, &mut known_to_be_outside_svg_resources) {
            return Err(VisualContextUpdateScope::EveryBox);
        }
        let mut bits = *bits;
        if layout_arena.node_kind_if_live(*slot) == Some(NodeKind::SVGSVGBox) && !bits.is_value_only() {
            bits.insert(VisualContextBoxDirtyKind::MovedWithDescendants);
        }
        work.entry(*slot).or_default().merge(bits);
    }
    let mut revalidate_children_of = HashSet::default();
    for removed in &dirty.removed {
        if layout_arena.paintable_row_is_populated(removed.former_paint_parent) {
            revalidate_children_of.insert(removed.former_paint_parent);
        }
    }
    // Only style and tree changes can change a stacking context's blending descendants.
    // A dirty box is already rebuilt. Start at its parent since the box's own blend, or a change in whether it
    // establishes a stacking context, can change its enclosing group's isolation too.
    let changed: Vec<_> = work
        .iter()
        .filter_map(|(slot, bits)| {
            (bits.contains(VisualContextBoxDirtyKind::NewRow)
                || bits.contains(VisualContextBoxDirtyKind::RecommittedInPlace)
                || bits.contains(VisualContextBoxDirtyKind::ReattachedInLayoutTree)
                || bits.contains(VisualContextBoxDirtyKind::StyleValueChange)
                || bits.contains(VisualContextBoxDirtyKind::StyleStructuralChange))
            .then(|| layout_arena.node_parent_if_live(*slot))
            .flatten()
        })
        .chain(revalidate_children_of.iter().copied())
        .collect();
    let mut visited = HashSet::default();
    for slot in changed {
        let mut ancestor = Some(slot);
        while let Some(parent) = ancestor {
            if !visited.insert(parent) {
                break;
            }
            if crate::painting::style_queries::establishes_stacking_context(layout_arena, parent) {
                work.entry(parent)
                    .or_default()
                    .insert(VisualContextBoxDirtyKind::StyleValueChange);
                break;
            }
            ancestor = layout_arena.node_parent_if_live(parent);
        }
    }
    // The offset transform of a box with an offset path depends on the geometry and style of its containing block,
    // so the box is rebuilt whenever its containing block is.
    let offset_path_boxes_to_rebuild: Vec<_> = offset_path_boxes
        .iter()
        .copied()
        .filter(|slot| {
            !work.contains_key(slot)
                && layout_arena.paintable_row_is_populated(*slot)
                && layout_arena
                    .node_containing_block_if_live(*slot)
                    .is_some_and(|containing_block| work.contains_key(&containing_block))
        })
        .collect();
    for slot in offset_path_boxes_to_rebuild {
        work.entry(slot)
            .or_default()
            .insert(VisualContextBoxDirtyKind::OffsetPathContainingBlockChanged);
    }
    let mut plan = WorkPlan {
        work,
        revalidate_children_of,
        ancestors_of_work: HashSet::default(),
    };
    let dirty_slots: Vec<NodeSlotId> = plan
        .work
        .keys()
        .copied()
        .chain(plan.revalidate_children_of.iter().copied())
        .collect();
    for slot in dirty_slots {
        plan.insert_ancestors_of_work(layout_arena, slot);
    }
    plan.add_anchored_boxes_below_dirty_scroll_chains(layout_arena);
    Ok(plan)
}

impl WorkPlan {
    fn insert_ancestors_of_work(&mut self, layout_arena: &impl PaintableRowsRead, slot: NodeSlotId) {
        let mut ancestor = paint_order::paint_parent(layout_arena, slot);
        while let Some(current) = ancestor {
            if !self.ancestors_of_work.insert(current) {
                break;
            }
            ancestor = paint_order::paint_parent(layout_arena, current);
        }
    }

    fn box_or_paint_ancestor_is_dirty(&self, layout_arena: &impl PaintableRowsRead, slot: NodeSlotId) -> bool {
        let mut node = layout_arena.paintable_row_is_populated(slot).then_some(slot);
        while let Some(current) = node {
            if self.work.contains_key(&current) || self.revalidate_children_of.contains(&current) {
                return true;
            }
            node = paint_order::paint_parent(layout_arena, current);
        }
        false
    }

    // An anchor-positioned box's scroll shift nodes name the scroll-like nodes between its own
    // scroll chain and its anchor's. A box above the anchor or above the positioned box changes
    // those chains without its rebuild reaching the positioned box, so the box is rebuilt
    // whenever either chain holds a dirty box.
    fn add_anchored_boxes_below_dirty_scroll_chains(&mut self, layout_arena: &impl PaintableRowsRead) {
        if !layout_arena.may_have_default_scroll_shift_anchor() {
            return;
        }
        let mut anchored_boxes: Vec<(NodeSlotId, NodeSlotId)> = Vec::new();
        layout_arena
            .for_each_default_scroll_shift_anchor(|positioned, anchor| anchored_boxes.push((positioned, anchor)));
        loop {
            let mut added_any = false;
            for &(positioned, anchor) in &anchored_boxes {
                if self.work.contains_key(&positioned) || !layout_arena.paintable_row_is_populated(positioned) {
                    continue;
                }
                if !self.box_or_paint_ancestor_is_dirty(layout_arena, anchor)
                    && !self.box_or_paint_ancestor_is_dirty(layout_arena, positioned)
                {
                    continue;
                }
                self.work
                    .entry(positioned)
                    .or_default()
                    .insert(VisualContextBoxDirtyKind::DefaultScrollShiftInputsChanged);
                self.insert_ancestors_of_work(layout_arena, positioned);
                added_any = true;
            }
            if !added_any {
                break;
            }
        }
    }
}

fn tombstone_removed_blocks(
    tree: &mut VisualContextTree,
    dirty: &VisualContextDirtySet,
    delta: &mut VisualContextTreeDelta,
    mut trace: Option<&mut super::trace::VisualContextTrace>,
) {
    use super::reconcile::{NodeAction, NodeEvent, clip_role, effect_role, spatial_role};
    for removed in &dirty.removed {
        let mut events = Vec::new();
        let mut released = |role: &'static str| {
            events.push(NodeEvent {
                role,
                action: NodeAction::Released,
            });
        };
        for index in &removed.node_handles.spatial {
            let role = spatial_role(&tree.spatial_nodes[index.0 as usize].data);
            if tree.tombstone_spatial_slot(*index) {
                delta.note_tombstoned();
                released(role);
            }
        }
        for index in removed.node_handles.clip_handles() {
            let role = clip_role(&tree.clip_nodes[index.0 as usize].data);
            if tree.tombstone_clip_slot(index) {
                delta.note_tombstoned();
                released(role);
            }
        }
        for index in &removed.node_handles.effects {
            let role = effect_role(&tree.effect_nodes[index.0 as usize].data);
            if tree.tombstone_effect_slot(*index) {
                delta.note_tombstoned();
                released(role);
            }
        }
        if let Some(trace) = trace.as_deref_mut() {
            trace.note_removed_box_events(removed.slot, &events);
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RegisteredScrollLikeNode {
    Scroll,
    Sticky,
}

pub(crate) fn register_scroll_like_node(
    layout_arena: &impl PaintableRowsRead,
    tree: &mut VisualContextTree,
    scroll_state: &mut ScrollState,
    node_index: SpatialNodeIndex,
) -> Option<RegisteredScrollLikeNode> {
    let index = node_index.0 as usize;
    let (owner_paintable, parent_of_sticky_node) = match &tree.spatial_nodes[index].data {
        SpatialData::Scroll(scroll) => (scroll.owner_paintable, None),
        SpatialData::Sticky(sticky) => (sticky.owner_paintable, Some(sticky.parent_sticky_or_scroller())),
        _ => return None,
    };
    if let Some(parent_of_sticky_node) = parent_of_sticky_node {
        let parent_slot = tree.scroll_state_slot_for_node(parent_of_sticky_node);
        let slot = scroll_state.register_sticky_node(node_index, owner_paintable, parent_slot);
        if let SpatialData::Sticky(sticky) = &mut tree.spatial_nodes[index].data {
            sticky.state_slot = slot;
        }
        Some(RegisteredScrollLikeNode::Sticky)
    } else {
        let slot = scroll_state.register_scroll_node(node_index, owner_paintable);
        if let SpatialData::Scroll(scroll) = &mut tree.spatial_nodes[index].data {
            scroll.state_slot = slot;
        }
        if layout_arena.node_kind_if_live(owner_paintable) != Some(NodeKind::Viewport)
            && let Some(style) = layout_arena.node_style_if_live(owner_paintable)
        {
            use crate::css::css_enums::overflow;
            if matches!(style.overflow_x(), overflow::AUTO | overflow::SCROLL)
                || matches!(style.overflow_y(), overflow::AUTO | overflow::SCROLL)
                || crate::painting::chrome_geometry::keeps_scrolls_along_some_axis(layout_arena, owner_paintable)
            {
                scroll_state.has_non_viewport_wheel_scroll_target_candidate = true;
            }
        }
        Some(RegisteredScrollLikeNode::Scroll)
    }
}

pub(crate) fn rebuild_scroll_state_from_tree(
    layout_arena: &impl PaintableRowsRead,
    tree: &mut VisualContextTree,
    tree_inputs: &FfiVisualContextTreeInputs,
) -> ScrollState {
    let mut scroll_state = ScrollState::default();
    for node_index in tree.spatial_dependency_order() {
        let node_index = SpatialNodeIndex(node_index);
        if register_scroll_like_node(layout_arena, tree, &mut scroll_state, node_index)
            != Some(RegisteredScrollLikeNode::Sticky)
        {
            continue;
        }
        let index = node_index.0 as usize;
        let SpatialData::Sticky(sticky) = &tree.spatial_nodes[index].data else {
            unreachable!("a registered sticky node keeps its payload kind");
        };
        tree.spatial_nodes[index].data = SpatialData::Sticky(compute_sticky_data(
            layout_arena,
            &scroll_state,
            sticky.state_slot,
            tree_inputs,
        ));
    }
    scroll_state
}

pub(crate) fn box_owns_geometry_dependent_nodes(
    layout_arena: &impl PaintableRowsRead,
    tree: &VisualContextTree,
    slot: NodeSlotId,
    has_svg_filter_bounds: bool,
    handles: &BoxVisualContextNodeHandles,
) -> bool {
    if has_svg_filter_bounds {
        return true;
    }
    let spatial_is_geometry_dependent = handles.spatial.iter().any(|index| {
        matches!(
            tree.spatial_nodes[index.0 as usize].data,
            SpatialData::Transform(_) | SpatialData::Perspective(_) | SpatialData::Sticky(_)
        )
    });
    let effects_filter_is_resolved_by_the_host_against_geometry = layout_arena
        .node_style_if_live(slot)
        .is_some_and(|style| crate::painting::css_filter::contains_url(&style.effects().filter));
    let clips_are_geometry_dependent = handles
        .clip_handles()
        .any(|index| tree.clip_nodes[index.0 as usize].data.is_live());
    let effects_are_geometry_dependent = handles.effects.iter().any(|index| {
        let node = &tree.effect_nodes[index.0 as usize];
        match &node.data {
            EffectNodeData::BackgroundColorAnimation => false,
            EffectNodeData::Mask(_) => true,
            EffectNodeData::Effects(effects) => {
                effects.backdrop_filter.is_some()
                    || (effects.filter.is_some() && effects_filter_is_resolved_by_the_host_against_geometry)
            }
            EffectNodeData::Dead => false,
        }
    });
    spatial_is_geometry_dependent || clips_are_geometry_dependent || effects_are_geometry_dependent
}

/// Whether the box owns no node, and its style and kind have its geometry give it none: a box like that keeps its
/// record and its contexts however its geometry changes.
fn box_keeps_no_node_whatever_its_geometry(layout_arena: &impl PaintableRowsRead, slot: NodeSlotId) -> bool {
    use crate::painting::style_queries;
    let owns_a_node = layout_arena
        .paintable_visual_context_node_handles(slot)
        .is_some_and(|handles| {
            !handles.spatial.is_empty()
                || !handles.chain_clips.is_empty()
                || !handles.descendant_clips.is_empty()
                || !handles.effects.is_empty()
        });
    if owns_a_node {
        return false;
    }
    // NB: The scroll shift nodes of an anchor-positioned box follow the scroll chain of its anchor, which a change
    //     above the anchor gives new nodes while the box itself only has new geometry.
    if !layout_arena.default_scroll_shift_anchor(slot).is_invalid() {
        return false;
    }
    let Some(kind) = layout_arena.node_kind_if_live(slot) else {
        return false;
    };
    // NB: An SVG box takes transforms, masks and a viewport from its layout.
    if style_queries::kind_is_svg_element_box(kind) || crate::painting::node_painting::supports_svg_masking(kind) {
        return false;
    }
    let Some(style) = layout_arena.node_style_if_live(slot) else {
        return false;
    };
    let transform = style.transform();
    let effects = style.effects();
    // NB: Each of these has a node whose existence the geometry of the box decides, like the backdrop filter of a box
    //     with an empty border box, or a clip only a box with scrollable overflow has.
    if transform.resolved_transforms.length != 0
        || transform.has_offset_path
        || transform.has_perspective
        || effects.filter.operations.length != 0
        || effects.backdrop_filter.operations.length != 0
        || effects.clip_is_rect
        || style_queries::clip_path_has_value(style.mask())
        || style_queries::mask_layers_have_image(style.mask())
        || super::node_values::may_have_clip(layout_arena, slot)
        || crate::painting::paintable_geometry::has_scrollable_overflow(layout_arena, slot)
    {
        return false;
    }
    layout_arena.with_committed_fragment_link(slot, |link| {
        link.is_some_and(|link| {
            link.placement.shown_as.facts.clip_decided_by_parent.is_none() && link.fragment.svg().is_none()
        })
    })
}

/// Whether the update builds a box that keeps no node anyway, to assert that the build changes nothing.
const CHECKS_BOXES_THAT_KEEP_NO_NODE: bool = cfg!(debug_assertions);

struct PendingBox {
    slot: NodeSlotId,
    input: DescendantVisualContexts,
    cascade: ChildCascade,
}

struct DeferredAnchorPositionedBox {
    pending: PendingBox,
    anchor: NodeSlotId,
}

struct WalkAnchorScrollShiftResolver<'a, Arena> {
    layout_arena: &'a Arena,
    assignments: &'a [PaintableVisualContextAssignment],
    assignment_index_by_slot: &'a HashMap<NodeSlotId, usize>,
}

impl<Arena: PaintableRowsRead> AnchorScrollShiftResolver for WalkAnchorScrollShiftResolver<'_, Arena> {
    fn default_scroll_shift_anchor(&self, slot: NodeSlotId) -> NodeSlotId {
        self.layout_arena.default_scroll_shift_anchor(slot)
    }

    fn spatial_node_index(&self, slot: NodeSlotId) -> SpatialNodeIndex {
        if let Some(&index) = self.assignment_index_by_slot.get(&slot) {
            return self.assignments[index].accumulated_visual_context.spatial;
        }
        // A box this pass has not rebuilt keeps the record of the tree being updated. A fresh
        // tree dropped every record; a box reached there before its own build is only reachable
        // through a malformed anchor chain and contributes no scroll shift.
        if self.layout_arena.paintable_visual_context_record(slot).is_some() {
            self.layout_arena
                .paintable_data(slot)
                .accumulated_visual_context
                .spatial
        } else {
            VISUAL_VIEWPORT_NODE_INDEX
        }
    }
}

fn anchor_is_awaiting_build(
    layout_arena: &impl PaintableRowsRead,
    anchor_node: NodeSlotId,
    awaiting: &HashSet<NodeSlotId>,
) -> bool {
    let mut paintable = layout_arena
        .paintable_row_is_populated(anchor_node)
        .then_some(anchor_node);
    while let Some(current) = paintable {
        if awaiting.contains(&current) {
            return true;
        }
        paintable = paint_order::paint_parent(layout_arena, current);
    }
    false
}

fn take_next_deferred_anchor_positioned(
    layout_arena: &impl PaintableRowsRead,
    deferred: &mut Vec<DeferredAnchorPositionedBox>,
    awaiting: &mut HashSet<NodeSlotId>,
) -> Option<PendingBox> {
    if deferred.is_empty() {
        return None;
    }
    // Cyclic or otherwise malformed anchor chains can leave every entry waiting on another;
    // the first entry is then built in queue order.
    let ready_position = deferred
        .iter()
        .position(|entry| !anchor_is_awaiting_build(layout_arena, entry.anchor, awaiting))
        .unwrap_or(0);
    let entry = deferred.remove(ready_position);
    awaiting.remove(&entry.pending.slot);
    Some(entry.pending)
}

pub(crate) fn update_visual_context_tree<Arena: PaintableRowsWrite>(
    layout_arena: &mut Arena,
    viewport: NodeSlotId,
    tree_inputs: FfiVisualContextTreeInputs,
    scope: VisualContextUpdateScope,
    state: &mut VisualContextState,
) -> IncrementalUpdateResult {
    let plan = if scope.rebuilds_every_box() {
        WorkPlan::default()
    } else {
        match expand_dirty_entries(&*layout_arena, &state.dirty_boxes, &state.offset_path_boxes) {
            Ok(plan) => plan,
            Err(reason) => return IncrementalUpdateResult::NeedsFullBuild(reason),
        }
    };
    let Some(tree) = state.tree.as_mut() else {
        return IncrementalUpdateResult::NeedsFullBuild(VisualContextUpdateScope::FreshTree);
    };
    let mut delta = VisualContextTreeDelta::default();
    debug_assert!(
        scope != VisualContextUpdateScope::FreshTree || state.dirty_boxes.removed.is_empty(),
        "removed handles name nodes of the discarded tree"
    );
    tombstone_removed_blocks(
        std::sync::Arc::make_mut(tree),
        &state.dirty_boxes,
        &mut delta,
        state.trace.as_mut(),
    );
    if scope.rebuilds_every_box() {
        state.offset_path_boxes.clear();
    }

    let viewport_output = layout_arena
        .paintable_visual_context_record(viewport)
        .map(|record| record.output_for_descendants);
    let Some(viewport_output) = viewport_output else {
        return IncrementalUpdateResult::NeedsFullBuild(VisualContextUpdateScope::FreshTree);
    };
    if scope.rebuilds_every_box() {
        std::sync::Arc::make_mut(tree)
            .set_visual_viewport_transform(super::node_values::visual_viewport_transform_data(&tree_inputs));
    }
    let every_box_capacity = if scope.rebuilds_every_box() {
        layout_arena.paintable_row_count()
    } else {
        0
    };
    let mut assignments: Vec<PaintableVisualContextAssignment> = Vec::with_capacity(every_box_capacity);
    let mut assignment_index_by_slot: HashMap<NodeSlotId, usize> =
        HashMap::with_capacity_and_hasher(every_box_capacity, Default::default());
    let mut stack: Vec<PendingBox> = Vec::new();
    let push_children = |layout_arena: &Arena,
                         stack: &mut Vec<PendingBox>,
                         parent: NodeSlotId,
                         input_for_children: DescendantVisualContexts,
                         cascade: ChildCascade,
                         visit_every_child: bool| {
        let pushed_children_begin = stack.len();
        paint_order::for_each_paint_child(layout_arena, parent, |child| {
            if visit_every_child || plan.work.contains_key(&child) || plan.ancestors_of_work.contains(&child) {
                stack.push(PendingBox {
                    slot: child,
                    input: input_for_children,
                    cascade,
                });
            }
        });
        stack[pushed_children_begin..].reverse();
    };
    push_children(
        &*layout_arena,
        &mut stack,
        viewport,
        viewport_output,
        ChildCascade::default(),
        scope.rebuilds_every_box() || plan.revalidate_children_of.contains(&viewport),
    );

    // An anchor-positioned box's scroll shift nodes name the scroll-like nodes above its anchor, so
    // the box is built once the stack is drained, after every anchor this pass rebuilds.
    let defers_anchor_positioned = layout_arena.may_have_default_scroll_shift_anchor();
    let mut deferred_anchor_positioned: Vec<DeferredAnchorPositionedBox> = Vec::new();
    let mut deferred_awaiting_build: HashSet<NodeSlotId> = HashSet::default();
    loop {
        let (pending, may_defer_this_box) = match stack.pop() {
            Some(pending) => (pending, defers_anchor_positioned),
            None => match take_next_deferred_anchor_positioned(
                &*layout_arena,
                &mut deferred_anchor_positioned,
                &mut deferred_awaiting_build,
            ) {
                Some(pending) => (pending, false),
                None => break,
            },
        };
        let slot = pending.slot;
        let input = pending.input;
        let work_bits = plan.work.get(&slot).copied();
        // A box that only moved changes no more than the boxes a moved ancestor carries along: only the nodes that
        // depend on its geometry.
        let moved = pending.cascade.geometry_walk || work_bits.is_some_and(|bits| bits.is_move_only());
        let (rebuild, keeps_no_node, subtree_may_own_geometry_dependent_nodes) = if scope.rebuilds_every_box() {
            (true, false, false)
        } else {
            let record = layout_arena.paintable_visual_context_record(slot);
            let rebuild = work_bits.is_some_and(|bits| !bits.is_move_only())
                || record.is_none_or(|record| record.inherited_input != input)
                || (moved && record.is_some_and(|record| record.owns_geometry_dependent_nodes));
            // OPTIMIZATION: A relayout changes the geometry of most boxes of a document, and most of them own no node:
            //               a box like that whose style has its geometry give it none keeps what it has.
            let keeps_no_node = rebuild
                && work_bits.is_some_and(|bits| bits.changes_geometry_only())
                && record.is_some_and(|record| record.inherited_input == input)
                && box_keeps_no_node_whatever_its_geometry(&*layout_arena, slot);
            (
                rebuild,
                keeps_no_node,
                record.is_some_and(|record| record.subtree_may_own_geometry_dependent_nodes),
            )
        };
        // NB: A build with debug assertions builds such a box anyway, and asserts that the build changed nothing.
        let rebuild = rebuild && (!keeps_no_node || CHECKS_BOXES_THAT_KEEP_NO_NODE);
        if rebuild && may_defer_this_box {
            let anchor = layout_arena.default_scroll_shift_anchor(slot);
            if !anchor.is_invalid() {
                deferred_awaiting_build.insert(slot);
                deferred_anchor_positioned.push(DeferredAnchorPositionedBox { pending, anchor });
                continue;
            }
        }
        let (child_cascade, output_for_children) = if rebuild {
            let (record_existed, previous_output, previous_stacking_context_facts) = {
                let existing_record = layout_arena.paintable_visual_context_record(slot);
                (
                    existing_record.is_some(),
                    existing_record.as_ref().map(|record| record.output_for_descendants),
                    existing_record.as_ref().map(|record| record.stacking_context),
                )
            };
            let tree = std::sync::Arc::make_mut(state.tree.as_mut().expect("the tree exists throughout the pass"));
            let existing_handles = layout_arena.paintable_visual_context_node_handles(slot);
            let mut writer = BoxNodeWriter::new(tree, existing_handles, &mut delta);
            if state.trace.is_some() && scope != VisualContextUpdateScope::FreshTree {
                writer.note_events();
            }
            let environment = BoxBuildEnvironment {
                layout_arena: &*layout_arena,
                pixel_ratio: tree_inputs.device_pixels_per_css_pixel,
            };
            let mut assignment = build_box_visual_context_nodes(
                &environment,
                &mut writer,
                slot,
                input,
                &WalkAnchorScrollShiftResolver {
                    layout_arena: &*layout_arena,
                    assignments: &assignments,
                    assignment_index_by_slot: &assignment_index_by_slot,
                },
            );
            let (handles, reconcile) = writer.finish();
            if keeps_no_node {
                let record = layout_arena
                    .paintable_visual_context_record(slot)
                    .expect("a box that keeps no node has a record");
                let data = layout_arena.paintable_data(slot);
                assert!(
                    !reconcile.shape_changed
                        && handles.spatial.is_empty()
                        && handles.clip_handles().next().is_none()
                        && handles.effects.is_empty()
                        && assignment.record.output_for_descendants == record.output_for_descendants
                        && assignment.accumulated_visual_context == data.accumulated_visual_context
                        && assignment.accumulated_visual_context_for_descendants
                            == data.accumulated_visual_context_for_descendants
                        && assignment.own_scroll_node_index == data.own_scroll_node_index
                        && assignment
                            .record
                            .stacking_context
                            .same_contributions_as(&record.stacking_context),
                    "the geometry of a box that keeps no node changed its visual contexts"
                );
            }
            let events = writer.take_events();
            if !events.is_empty()
                && let Some(trace) = state.trace.as_mut()
            {
                trace.note_box_events(slot, &events);
            }
            if layout_arena
                .node_style_if_live(slot)
                .is_some_and(|style| style.transform().has_offset_path)
            {
                state.offset_path_boxes.insert(slot);
            } else {
                state.offset_path_boxes.remove(&slot);
            }
            let new_output = assignment.record.output_for_descendants;
            assignment.node_handles = handles;
            assignment.record.owns_geometry_dependent_nodes = box_owns_geometry_dependent_nodes(
                &*layout_arena,
                tree,
                slot,
                assignment.gathered_svg_filter_bounds.flatten().is_some(),
                &assignment.node_handles,
            );
            assignment.record.subtree_may_own_geometry_dependent_nodes =
                assignment.record.owns_geometry_dependent_nodes || subtree_may_own_geometry_dependent_nodes;
            if scope != VisualContextUpdateScope::FreshTree {
                let box_was_reattached =
                    work_bits.is_some_and(|bits| bits.contains(VisualContextBoxDirtyKind::ReattachedInLayoutTree));
                layout_arena.apply_stacking_context_facts_delta(
                    slot,
                    previous_stacking_context_facts.as_ref(),
                    &mut assignment.record.stacking_context,
                    box_was_reattached,
                );
            }

            let previous_contexts = record_existed.then(|| {
                let data = layout_arena.paintable_data(slot);
                (
                    data.accumulated_visual_context,
                    data.accumulated_visual_context_for_descendants,
                )
            });
            let contexts_changed = previous_contexts
                != Some((
                    assignment.accumulated_visual_context,
                    assignment.accumulated_visual_context_for_descendants,
                ));
            // A box can select different inherited nodes without owning any nodes itself.
            // Its recorded contexts must still be replaced in the next display list.
            delta.requires_display_list_recording |= contexts_changed;
            if reconcile.shape_changed || !record_existed || contexts_changed {
                layout_arena.note_paint_change(slot, RowPaintChange::EVERYTHING_IT_PAINTS);
            }
            if assignment.record.owns_geometry_dependent_nodes && !subtree_may_own_geometry_dependent_nodes {
                let mut ancestor = paint_order::paint_parent(&*layout_arena, slot);
                while let Some(current) = ancestor {
                    let ancestor_was_flagged = if let Some(&index) = assignment_index_by_slot.get(&current) {
                        let flagged = assignments[index].record.subtree_may_own_geometry_dependent_nodes;
                        assignments[index].record.subtree_may_own_geometry_dependent_nodes = true;
                        flagged
                    } else {
                        layout_arena
                            .mark_paintable_subtree_may_own_geometry_dependent_nodes(current)
                            .unwrap_or(true)
                    };
                    if ancestor_was_flagged {
                        break;
                    }
                    ancestor = paint_order::paint_parent(&*layout_arena, current);
                }
            }
            assignment_index_by_slot.insert(slot, assignments.len());
            assignments.push(assignment);
            let cascade = ChildCascade {
                input_changed: previous_output != Some(new_output),
                geometry_walk: pending.cascade.geometry_walk || work_bits.is_some_and(|bits| bits.moves_descendants()),
            };
            (cascade, Some(new_output))
        } else {
            let moves_descendants =
                pending.cascade.geometry_walk || work_bits.is_some_and(|bits| bits.moves_descendants());
            let cascade = ChildCascade {
                input_changed: false,
                geometry_walk: moves_descendants && subtree_may_own_geometry_dependent_nodes,
            };
            (cascade, None)
        };
        let revalidate_children = plan.revalidate_children_of.contains(&slot);
        let visit_every_child = scope.rebuilds_every_box() || child_cascade.visits_every_child() || revalidate_children;
        if visit_every_child || plan.ancestors_of_work.contains(&slot) {
            let output_for_children = output_for_children.unwrap_or_else(|| {
                layout_arena
                    .paintable_visual_context_record(slot)
                    .expect("a box that was not rebuilt keeps its record")
                    .output_for_descendants
            });
            push_children(
                &*layout_arena,
                &mut stack,
                slot,
                output_for_children,
                child_cascade,
                visit_every_child,
            );
        }
    }

    let tree = std::sync::Arc::make_mut(state.tree.as_mut().expect("the tree exists throughout the pass"));
    if incremental_tree_requires_fresh_build(tree, &delta) {
        return IncrementalUpdateResult::NeedsFullBuild(VisualContextUpdateScope::FreshTree);
    }
    debug_assert!(tree.node_references_are_consistent());
    let scroll_state = rebuild_scroll_state_from_tree(&*layout_arena, tree, &tree_inputs);
    tree.debug_assert_slot_accounting();
    if delta.structural_epoch_changed {
        tree.structural_epoch = allocate_structural_epoch();
        // The animations name nodes of the epoch they were published with; the main thread
        // publishes them again for this one.
        tree.clear_visual_animations();
    }
    // Whether any box but the viewport could take or keep a wheel event decides if scroll metadata
    // everywhere carries per-box wheel targets.
    if state.scroll_state.has_non_viewport_wheel_scroll_target_candidate
        != scroll_state.has_non_viewport_wheel_scroll_target_candidate
    {
        layout_arena.note_everything_paints_anew();
    }
    state.scroll_state = scroll_state;
    state.needs_to_refresh_scroll_state = true;
    IncrementalUpdateResult::Applied(Box::new(IncrementalUpdateOutcome { delta, assignments }))
}

#[cfg(debug_assertions)]
pub(crate) fn debug_assert_every_live_node_is_owned(
    layout_arena: &impl PaintableRowsRead,
    tree: &VisualContextTree,
    viewport: NodeSlotId,
) {
    let mut spatial_is_owned = vec![false; tree.spatial_nodes.len()];
    let mut clip_is_owned = vec![false; tree.clip_nodes.len()];
    let mut effect_is_owned = vec![false; tree.effect_nodes.len()];
    spatial_is_owned[VISUAL_VIEWPORT_NODE_INDEX.0 as usize] = true;
    let viewport_scroll_node = layout_arena.paintable_data(viewport).own_scroll_node_index;
    if (viewport_scroll_node.0 as usize) < spatial_is_owned.len() {
        spatial_is_owned[viewport_scroll_node.0 as usize] = true;
    }
    if let Some(root_isolation_effect) = tree.root_isolation_effect {
        effect_is_owned[root_isolation_effect.0 as usize] = true;
    }
    fn claim(owned: &mut [bool], index: u32, kind: &str) {
        assert!(!owned[index as usize], "{kind} {index} is claimed twice");
        owned[index as usize] = true;
    }
    paint_order::for_each_in_paint_subtree(layout_arena, viewport, |slot| {
        let Some(handles) = layout_arena.paintable_visual_context_node_handles(slot) else {
            return;
        };
        for index in &handles.spatial {
            claim(&mut spatial_is_owned, index.0, "spatial node");
        }
        for index in handles.clip_handles() {
            claim(&mut clip_is_owned, index.0, "clip node");
        }
        for index in &handles.effects {
            claim(&mut effect_is_owned, index.0, "effect node");
        }
    });
    for (index, node) in tree.spatial_nodes.iter().enumerate() {
        assert!(
            !node.data.is_live() || spatial_is_owned[index],
            "live spatial node {index} has no owner"
        );
    }
    for (index, node) in tree.clip_nodes.iter().enumerate() {
        assert!(
            !node.data.is_live() || clip_is_owned[index],
            "live clip node {index} has no owner"
        );
    }
    for (index, node) in tree.effect_nodes.iter().enumerate() {
        assert!(
            !node.data.is_live() || effect_is_owned[index],
            "live effect node {index} has no owner"
        );
    }
}

#[cfg(not(debug_assertions))]
pub(crate) fn debug_assert_every_live_node_is_owned(
    _layout_arena: &impl PaintableRowsRead,
    _tree: &VisualContextTree,
    _viewport: NodeSlotId,
) {
}

#[cfg(test)]
mod tests {
    use super::*;
    use libgfx_rust::{CompositingAndBlendingOperator, FloatMatrix4x4};
    use libgfx_rust::{FloatPoint, FloatRect};

    fn effects() -> EffectNodeData {
        EffectNodeData::Effects(EffectsData {
            isolation: false,
            opacity: 0.5,
            blend_mode: CompositingAndBlendingOperator::Normal,
            filter: None,
            backdrop_filter: None,
        })
    }

    fn tree() -> VisualContextTree {
        VisualContextTree::create(TransformData {
            matrix: FloatMatrix4x4::identity(),
            origin: FloatPoint::default(),
            sorting_context_root_index: None,
            flattens_inherited_transform: false,
            role: TransformDataRole::CssTransform,
            synthetic_plane: false,
            establishes_sorting_context: false,
            bounds: FloatRect::default(),
        })
    }

    #[test]
    fn a_tombstoned_parent_of_a_live_effect_requires_a_fresh_tree() {
        let mut tree = tree();
        let parent = tree.append_effect(
            effects(),
            EffectNodeIndex::NONE,
            VISUAL_VIEWPORT_NODE_INDEX,
            ClipNodeIndex::NONE,
        );
        tree.append_effect(effects(), parent, VISUAL_VIEWPORT_NODE_INDEX, ClipNodeIndex::NONE);

        let mut delta = VisualContextTreeDelta::default();
        assert!(tree.tombstone_effect_slot(parent));
        delta.note_tombstoned();

        assert!(incremental_tree_requires_fresh_build(&tree, &delta));
    }

    #[test]
    fn a_context_naming_a_tombstoned_clip_is_rejected() {
        let mut tree = tree();
        let clip = tree.append_clip(
            ClipNodeData::rect_clip(FloatRect::new(0.0, 0.0, 1.0, 1.0)),
            ClipNodeIndex::NONE,
            VISUAL_VIEWPORT_NODE_INDEX,
        );
        let context = ContextRef {
            clip,
            ..ContextRef::default()
        };
        assert!(tree.context_is_valid(context));
        assert!(tree.tombstone_clip_slot(clip));
        assert!(!tree.context_is_valid(context));
    }
}