Skip to content

Truly independent web browser

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

//! The steps of paint preparation, as passes the host sends its document's render state and waits for. A pass reads
//! and writes the arena alone: what it owes the host, such as the scroll offsets it clamped, comes back in its answer.

use crate::css::css_pixels::CssPixelPoint;
use crate::layout::LayoutNodeArena;
use crate::layout::node_data::NodeSlotId;
use crate::painting::host::{FfiPaintPreparationHostCallbacks, FfiVisualContextTreeInputs, RootBackgroundSource};
use crate::painting::paint_read::PaintRead;
use crate::painting::svg_paint_resources::{PublishedSvgFilter, PublishedSvgPaintServer, SvgPaintResourceKind};
use crate::painting::visual_context::compositor_scroll_table::{
    CompositorScrollInputs, refresh_compositor_scroll_table,
};
use crate::painting::visual_context::dirty::VisualContextUpdateScope;
use crate::painting::visual_context::incremental::{
    IncrementalUpdateResult, debug_assert_every_live_node_is_owned, update_visual_context_tree,
};
use crate::painting::visual_context::{VisualContextState, VisualContextTree};
use crate::render_state::{BegunRead, DocumentHost};
use crate::stage::MainThread;
use libgfx_rust::{FloatPoint, IntSize};
use std::cell::Cell;
use std::sync::Arc;

/// What a paint pass writes, which decides what the host lets go of before it sends the pass, and whether the paint and
/// hit testing properties the host prepared stay current.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum PassEffect {
    /// Writes the rows throughout: measures every unmeasured overflow, or brings the visual context of every dirty box
    /// up to date. Such a pass is one of those that prepare the paint and hit testing properties.
    RewritesRows,
    /// Changes nothing the paint and hit testing properties are prepared from.
    KeepsPaintPreparation,
    /// Changes what the paint and hit testing properties are prepared from.
    StalesPaintPreparation,
}

impl PassEffect {
    pub(crate) fn leaves_paint_preparation_current(self) -> bool {
        self != Self::StalesPaintPreparation
    }
}

pub(crate) struct RenderingPreparationOutcome {
    pub(crate) requires_display_list_recording: bool,
    pub(crate) requires_visual_context_update: bool,
    pub(crate) visual_context_values_changed: bool,
}

#[derive(Default)]
pub(crate) struct CompositorScrollRefreshOutcome {
    pub(crate) table_changed: bool,
    pub(crate) requires_display_list_recording: bool,
}

#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct VisualContextUpdateOutcome {
    pub(crate) performed_full_build: bool,
    pub(crate) structural_epoch_changed: bool,
    pub(crate) requires_display_list_recording: bool,
    /// Whether the update may have given a node of the tree other values: it visited a dirty box, or every box.
    pub(crate) values_may_have_changed: bool,
}

/// What preparing for rendering answers: its outcome, and the scroll offsets the new overflow moved out of range,
/// each clamped into it, for the host to store.
pub(crate) struct RenderingPreparation {
    pub(crate) outcome: RenderingPreparationOutcome,
    pub(crate) clamped_scroll_offsets: Vec<(NodeSlotId, CssPixelPoint)>,
}

/// What a clock tick's round changed that only the host settles: a root background, scrollability or SVG paint
/// resource, a visual context tree built anew, or a compositor animation of a box the round built again.
pub(crate) struct VisualContextsNeedHost(pub(crate) &'static str);

/// The visual context tree a clock tick's frame takes to the compositor, and the scroll offsets of its nodes where the
/// tick updated it, which the frame was recorded with.
pub(crate) struct ClockTickVisualContexts {
    pub(crate) tree: Arc<VisualContextTree>,
    pub(crate) scroll_offsets: Option<Vec<FloatPoint>>,
    /// Whether the tree's structure is not the one the compositor has.
    pub(crate) restructured: bool,
}

/// Brings the paint state of `arena` up to date with what a clock tick's round laid out, for the tick's frame, as the
/// host's rendering update does before it records, where the round moved no root background, flipped no scrollability
/// and asks the host to resolve no SVG paint resource, and the update changes the tree incrementally. Answers the tree
/// where the update ran. A tree of a new structure carries the compositor animations the host published for the old one
/// over to the nodes of the same boxes. The rest of paint preparation, the scroll offsets new overflow clamps above all, is
/// the host's, in its next rendering update.
pub(crate) fn prepare_for_clock_tick(
    arena: &mut LayoutNodeArena,
    viewport: NodeSlotId,
) -> Result<Option<ClockTickVisualContexts>, VisualContextsNeedHost> {
    // Recording reads overflow, and settling it notes a flip in scrollability for the check below.
    arena.settle_scrollable_overflow();
    if arena.svg_paint_resources().needs_sync()
        || arena.paint_state().root_background_source
            != Some(crate::layout::viewport_propagation::root_background_source(arena))
    {
        return Err(VisualContextsNeedHost(
            "SVG paint resources or the root background moved",
        ));
    }
    let scroll_table_changed = arena.with_visual_context_state_lent(|arena, state| {
        if !state.dirty_boxes.boxes.is_empty()
            || !state.dirty_boxes.removed.is_empty()
            || state.dirty_boxes.scope.rebuilds_every_box()
        {
            return false;
        }
        state
            .last_compositor_scroll_inputs
            .is_some_and(|inputs| refresh_compositor_scroll_table(arena, state, inputs).table_changed)
    });
    let (inputs, compositor_animations) = {
        let paint_state = arena.paint_state_mut();
        let state = &mut paint_state.visual_context;
        let (Some(inputs), Some(tree)) = (state.last_tree_inputs, state.tree.as_deref()) else {
            return Err(VisualContextsNeedHost("no visual context tree"));
        };
        if state.dirty_boxes.scope.rebuilds_every_box() {
            return Err(VisualContextsNeedHost("every box rebuilds its visual contexts"));
        }
        if state.dirty_boxes.boxes.is_empty() && state.dirty_boxes.removed.is_empty() {
            // A tick that stopped compositor animations of the host's takes the tree without them to the compositor.
            if !scroll_table_changed && tree.visual_animations() == state.published_compositor_animations.as_slice() {
                return Ok(None);
            }
            state.published_compositor_animations = tree.visual_animations().to_vec();
            return Ok(Some(ClockTickVisualContexts {
                tree: state.tree.clone().expect("the tree is there"),
                scroll_offsets: None,
                restructured: false,
            }));
        }
        (inputs, tree.shared_visual_animations())
    };
    // The boxes the compositor animations drive nodes of, as the tree before the update holds them, which a tree of a
    // new structure gives other nodes.
    let before = (!compositor_animations.is_empty()).then(|| {
        let tree = arena.paint_state().visual_context.tree.clone();
        (
            arena.visual_context_node_handles_snapshot(),
            tree.expect("the tree is there"),
        )
    });
    keep_nodes_compositor_animations_drive(arena);
    let outcome = update_accumulated_visual_contexts(arena, viewport, inputs);
    if outcome.performed_full_build {
        return Err(VisualContextsNeedHost("a full visual context tree build"));
    }
    arena.with_visual_context_state_lent(|arena, state| {
        if let Some(inputs) = state.last_compositor_scroll_inputs {
            refresh_compositor_scroll_table(arena, state, inputs);
        }
        // NB: The update rebuilds the scroll state with every offset at zero, whether or not it changed the tree's
        //     structure, and the frame places its window around the viewport by those offsets: They're refreshed from
        //     layout here, so a pane scrolled down keeps what it shows in the window. The host takes the same offsets.
        let scroll_offsets = scroll_state_snapshot(&arena.paintable_rows(), state, inputs.device_pixels_per_css_pixel);
        let tree = state.tree.as_mut().expect("an incremental update keeps the tree");
        if !outcome.structural_epoch_changed {
            return Ok(Some(ClockTickVisualContexts {
                tree: tree.clone(),
                scroll_offsets: Some(scroll_offsets),
                restructured: false,
            }));
        }
        // The update dropped the animations, which name nodes of the old structure: each goes on driving the nodes of its
        // box in the new one. An animation of a box that has no node of its kind any more drives nothing the frame shows,
        // as the tick gave the box a style of its own for what it animates.
        if let Some((handles_before, tree_before)) = before {
            let animations = carry_visual_animations_to_new_nodes(
                arena,
                &handles_before,
                &tree_before,
                tree,
                &compositor_animations,
            )?;
            Arc::make_mut(tree).set_visual_animations(animations);
        }
        Ok(Some(ClockTickVisualContexts {
            tree: tree.clone(),
            scroll_offsets: Some(scroll_offsets),
            restructured: true,
        }))
    })
}

/// The compositor animations `animations`, which drive nodes of `tree_before`, whose boxes `handles_before` held, driving
/// the nodes of the same boxes in `tree`, a tree of a new structure. An animation of a box that has no node of its kind
/// in `tree` is dropped. One of a box the update built again, or took away, is the host's to go on with.
fn carry_visual_animations_to_new_nodes(
    arena: &LayoutNodeArena,
    handles_before: &crate::cow_column::ColumnSnapshot<
        Option<Arc<crate::painting::visual_context::records::BoxVisualContextNodeHandles>>,
        { crate::painting::paintable_rows::PAINTABLE_SLOTS_PER_CHUNK },
    >,
    tree_before: &VisualContextTree,
    tree: &VisualContextTree,
    animations: &[crate::painting::visual_animation::VisualAnimation],
) -> Result<Vec<crate::painting::visual_animation::VisualAnimation>, VisualContextsNeedHost> {
    use crate::painting::host::FfiVisualAnimationTargetKind;
    let mut effect_owners = std::collections::HashMap::new();
    let mut spatial_owners = std::collections::HashMap::new();
    for index in 0..handles_before.slot_capacity() {
        let Some(Some(handles)) = handles_before.get(index) else {
            continue;
        };
        for effect in &handles.effects {
            effect_owners.insert(effect.0, index as u32);
        }
        for spatial in &handles.spatial {
            spatial_owners.insert(spatial.0, index as u32);
        }
    }
    let mut carried = Vec::with_capacity(animations.len());
    for animation in animations {
        let owners = match animation.target_kind {
            FfiVisualAnimationTargetKind::Transform => &spatial_owners,
            _ => &effect_owners,
        };
        let mut targets = animation
            .node_indices
            .iter()
            .filter(|&&node| tree_before.visual_animation_target_is_valid(animation.target_kind, node))
            .peekable();
        // An animation that drove no node of the tree before drives nothing the frame shows.
        if targets.peek().is_none() {
            continue;
        }
        let owner = targets
            .find_map(|node| owners.get(node))
            .and_then(|&owner| arena.live_slot_at(owner))
            .ok_or(VisualContextsNeedHost("animations of a box built again"))?;
        let node_indices = arena.paintable_visual_animation_target_indices(owner, Some(tree), animation.target_kind);
        if !node_indices.is_empty() {
            carried.push(crate::painting::visual_animation::VisualAnimation {
                node_indices,
                ..animation.clone()
            });
        }
    }
    Ok(carried)
}

/// Has each box a clock tick restyled keep the effect node a compositor animation the host published drives, as the
/// host's frame had it: the host gave the box the node for a value its style held as the animation ran, which the tick's
/// style need not hold, where it did not force one for the animation.
fn keep_nodes_compositor_animations_drive(arena: &mut LayoutNodeArena) {
    use crate::layout::node_data::CompositorAnimationFrameKind;
    use crate::painting::host::FfiVisualAnimationTargetKind;
    let (dirty, animations) = {
        let paint_state = arena.paint_state();
        let state = &paint_state.visual_context;
        let Some(tree) = state.tree.as_deref().filter(|tree| tree.has_visual_animations()) else {
            return;
        };
        let dirty: Vec<NodeSlotId> = state.dirty_boxes.boxes.keys().copied().collect();
        (dirty, tree.shared_visual_animations())
    };
    for slot in dirty {
        let nodes = arena.box_animation_nodes(slot);
        if nodes.effects.is_empty() {
            continue;
        }
        for animation in animations.iter() {
            let kind = match animation.target_kind {
                FfiVisualAnimationTargetKind::Opacity | FfiVisualAnimationTargetKind::Filter => {
                    CompositorAnimationFrameKind::Opacity
                }
                FfiVisualAnimationTargetKind::BackgroundColor => CompositorAnimationFrameKind::BackgroundColor,
                FfiVisualAnimationTargetKind::Transform => continue,
            };
            if nodes.driven_by(animation) && !arena.node_has_compositor_animation_frame(slot, kind) {
                arena.set_node_needs_compositor_animation_frame(slot, kind, true);
            }
        }
    }
}

/// Runs `pass` over the render state of `host`'s document in `read`, as the host prepares to paint, and answers what it
/// answered.
pub(crate) fn run<R>(
    read: &BegunRead,
    host: &DocumentHost,
    effect: PassEffect,
    pass: impl FnOnce(&mut LayoutNodeArena) -> R,
) -> R {
    if effect == PassEffect::RewritesRows {
        host.let_go_of_rows();
    }
    host.run(read, !effect.leaves_paint_preparation_current(), move |state| {
        pass(state.arena_mut())
    })
}

/// Proof that preparing a document for rendering has something to do, which only [`rendering_preparation_pending`]
/// mints: a host never sends a preparation that would answer that nothing changed. It carries the root background
/// source it was found with, for the preparation to take over.
pub(crate) struct PendingPreparation {
    root_background_source: RootBackgroundSource,
}

impl PendingPreparation {
    /// Settles the scrollable overflow left unmeasured, and with it the root background and, with `sticky_inputs`, the
    /// sticky constraints.
    pub(crate) fn prepare(
        self,
        arena: &mut LayoutNodeArena,
        sticky_inputs: Option<&FfiVisualContextTreeInputs>,
    ) -> RenderingPreparation {
        prepare_for_rendering(arena, self.root_background_source, sticky_inputs)
    }
}

/// Whether preparing `arena` for rendering would change anything: its root background source moved, scrollable
/// overflow is left to settle, a stored scroll offset may have to be clamped, or an overflow change since the last
/// preparation changed what it answers.
pub(crate) fn rendering_preparation_pending(arena: &LayoutNodeArena) -> Option<PendingPreparation> {
    let root_background_source = crate::layout::viewport_propagation::root_background_source(arena);
    let overflow = &arena.scrollable_overflow;
    let pending = arena.paint_state().root_background_source != Some(root_background_source)
        || overflow.change_awaits_preparation()
        || !overflow.scroll_offset_clamp_candidates.is_empty()
        || !arena.scrollable_overflow_is_settled();
    pending.then_some(PendingPreparation { root_background_source })
}

/// Asks the render state of `host`'s document in `read` whether preparing it for rendering has something to do, unless
/// the host knows it has nothing.
pub(crate) fn pending_preparation(read: &BegunRead, host: &DocumentHost) -> Option<PendingPreparation> {
    if host
        .known_arena_facts()
        .is_some_and(|facts| !facts.rendering_preparation_pending)
    {
        return None;
    }
    host.ask(read, |state| rendering_preparation_pending(state.arena_mut()))
}

/// What the next preparation of a document's paint and hit testing properties owes, and what the ones before left for
/// the document's frames, which the document's host keeps.
#[derive(Default)]
pub(crate) struct PaintPreparationNotes {
    /// Whether the next preparation updates the visual contexts.
    pub(crate) visual_contexts_need_update: Cell<bool>,
    /// Whether the visual context tree changed since a frame last took it to the compositor.
    pub(crate) visual_context_tree_needs_compositor_update: Cell<bool>,
}

/// The document's viewport row, where its box is committed.
fn committed_viewport(arena: &LayoutNodeArena) -> Option<NodeSlotId> {
    let viewport = arena.bound_viewport_row();
    arena.paintable_row_is_populated(viewport).then_some(viewport)
}

/// Brings the paint and hit testing properties of `host`'s document up to date with its render state in `read`: the
/// scrollable overflow and root background, the visual contexts and the scroll state. Every entry that hands the host
/// what they are prepared into calls this first, and it returns at once where nothing was written to the render state
/// since they were prepared last.
pub(crate) fn prepare_paint_properties(main_thread: &MainThread, host: &DocumentHost, read: &BegunRead) {
    let notes = host.paint_preparation();
    if host.paint_preparation_is_current() && !notes.visual_contexts_need_update.get() {
        return;
    }
    let Some(callbacks) = host.host_tables().paint_preparation_host.get() else {
        return;
    };
    // What the passes prepare stays current until something is written to the render state, from here on as well.
    host.note_paint_preparation_is_current();

    settle_scrollable_overflow_and_root_background(main_thread, host, read, &callbacks);

    if notes.visual_contexts_need_update.replace(false) {
        update_visual_contexts(main_thread, host, read, &callbacks);
    }

    // Scroll nodes are (re)created by the visual context tree build above, so scroll offsets and the snapshot must be
    // derived only after structure work is done.
    let viewport = callbacks.viewport(main_thread);
    let refreshed = run(read, host, PassEffect::RewritesRows, |arena| {
        committed_viewport(arena)?;
        Some(refresh_scroll_state(
            arena,
            viewport.visual_context_tree_inputs.device_pixels_per_css_pixel,
            viewport.device_viewport_size,
        ))
    });
    let Some((device_offsets, outcome)) = refreshed else {
        return;
    };
    if let Some(device_offsets) = device_offsets {
        host.refresh_scroll_state(device_offsets);
    }
    if outcome.table_changed {
        notes.visual_context_tree_needs_compositor_update.set(true);
    }
    if outcome.requires_display_list_recording {
        callbacks.require_display_list_recording(main_thread, true);
    }
}

/// Settles the scrollable overflow and root background of `host`'s document where they are left to settle, and stores
/// the scroll offsets the new overflow moved out of range: the first step of preparing the paint and hit testing
/// properties, which a layout update that finds the layout up to date takes as well.
pub(crate) fn prepare_for_rendering_if_pending(main_thread: &MainThread, host: &DocumentHost, read: &BegunRead) {
    if let Some(callbacks) = host.host_tables().paint_preparation_host.get() {
        settle_scrollable_overflow_and_root_background(main_thread, host, read, &callbacks);
    }
}

fn settle_scrollable_overflow_and_root_background(
    main_thread: &MainThread,
    host: &DocumentHost,
    read: &BegunRead,
    callbacks: &FfiPaintPreparationHostCallbacks,
) {
    let Some(pending) = pending_preparation(read, host) else {
        return;
    };
    let notes = host.paint_preparation();
    let inputs = callbacks.viewport(main_thread).visual_context_tree_inputs;
    let visual_contexts_need_update = notes.visual_contexts_need_update.get();
    let prepared = run(read, host, PassEffect::RewritesRows, move |arena| {
        pending.prepare(arena, (!visual_contexts_need_update).then_some(&inputs))
    });
    if let Some(geometry_host) = host.host_tables().geometry_host.get() {
        for (slot, offset) in prepared.clamped_scroll_offsets {
            geometry_host.set_scroll_offset(main_thread, read, slot, offset.into());
        }
    }
    if prepared.outcome.requires_visual_context_update {
        notes.visual_contexts_need_update.set(true);
    }
    if prepared.outcome.visual_context_values_changed {
        notes.visual_context_tree_needs_compositor_update.set(true);
    }
    if prepared.outcome.requires_display_list_recording {
        callbacks.require_display_list_recording(main_thread, true);
    }
}

/// Brings the visual context tree of `host`'s document up to date, with the SVG paint resources it is built from, where
/// the document's viewport box is committed.
fn update_visual_contexts(
    main_thread: &MainThread,
    host: &DocumentHost,
    read: &BegunRead,
    callbacks: &FfiPaintPreparationHostCallbacks,
) {
    let Some(svg_paint_resources_changed) = sync_svg_paint_resources(main_thread, host, read, callbacks) else {
        return;
    };
    let inputs = callbacks.viewport(main_thread).visual_context_tree_inputs;
    let started = painting_timing_enabled().then(std::time::Instant::now);
    let outcome = run(read, host, PassEffect::RewritesRows, |arena| {
        committed_viewport(arena).map(|viewport| update_accumulated_visual_contexts(arena, viewport, inputs))
    });
    let Some(outcome) = outcome else {
        return;
    };
    if let Some(started) = started {
        eprintln!(
            "AVC_UPDATE rust={} µs {}",
            started.elapsed().as_micros(),
            if outcome.performed_full_build {
                "full"
            } else {
                "incremental"
            }
        );
    }
    let notes = host.paint_preparation();
    if outcome.requires_display_list_recording || svg_paint_resources_changed {
        callbacks.require_display_list_recording(main_thread, false);
    }
    if outcome.values_may_have_changed {
        notes.visual_context_tree_needs_compositor_update.set(true);
    }
}

fn painting_timing_enabled() -> bool {
    static PAINTING_TIMING_ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *PAINTING_TIMING_ENABLED.get_or_init(|| {
        std::env::var("LADYBIRD_RUST_PAINTING_TIMING").is_ok_and(|value| !value.is_empty() && value != "0")
    })
}

/// Resolves the SVG paint resources the enrolled rows of `host`'s document name: the render state answers what to
/// resolve, the document resolves it from the DOM, and the render state publishes what it resolved. Answers whether a
/// published resource changed, or nothing where the document's viewport box is not committed.
fn sync_svg_paint_resources(
    main_thread: &MainThread,
    host: &DocumentHost,
    read: &BegunRead,
    callbacks: &FfiPaintPreparationHostCallbacks,
) -> Option<bool> {
    let requests = run(read, host, PassEffect::KeepsPaintPreparation, |arena| {
        committed_viewport(arena)?;
        Some(svg_paint_resource_requests(arena))
    })?;
    let Some(requests) = requests else {
        return Some(false);
    };
    let resolved = requests
        .into_iter()
        .map(|request| match request {
            SvgPaintResourceRequest::PaintServer { slot, kind } => {
                let mut published = PublishedSvgPaintServer::None;
                callbacks.resolve_svg_paint_server(
                    main_thread,
                    read,
                    slot,
                    kind == SvgPaintResourceKind::Stroke,
                    &mut published,
                );
                ResolvedSvgPaintResource::PaintServer { slot, kind, published }
            }
            SvgPaintResourceRequest::Filter { slot, kind, urls } => {
                let mut published = PublishedSvgFilter::default();
                for url in &urls {
                    let mut candidate = PublishedSvgFilter::default();
                    let found =
                        callbacks.resolve_svg_filter(main_thread, read, slot, url.pointer().cast(), &mut candidate);
                    published = if found {
                        candidate
                    } else {
                        PublishedSvgFilter {
                            failed: true,
                            ..Default::default()
                        }
                    };
                    if published.failed {
                        break;
                    }
                }
                ResolvedSvgPaintResource::Filter { slot, kind, published }
            }
        })
        .collect();
    Some(run(read, host, PassEffect::StalesPaintPreparation, |arena| {
        publish_resolved_svg_paint_resources(arena, resolved)
    }))
}

/// Prepares `arena` for rendering. The sticky constraints the new overflow moved are refreshed with `sticky_inputs`, the
/// inputs of the visual context tree, unless there are none: a visual context update is pending, which refreshes them.
pub(crate) fn prepare_for_rendering(
    arena: &mut LayoutNodeArena,
    root_background_source: RootBackgroundSource,
    sticky_inputs: Option<&FfiVisualContextTreeInputs>,
) -> RenderingPreparation {
    let background_source_changed = arena.update_root_background_source(root_background_source);
    // This settles all overflow left to recalculate, including the root's: the root background covers
    // the viewport united with it, so a flip in its scrollability is seen here rather than while
    // recording holds the paint state.
    let clamped_scroll_offsets = crate::painting::scrollable_overflow::update_scrollable_overflow(arena);
    let changed = std::mem::replace(&mut arena.scrollable_overflow.geometry_changed, false);
    let flipped = std::mem::replace(&mut arena.scrollable_overflow.scrollability_changed, false);
    let mut visual_context_values_changed = false;
    if let Some(inputs) = sticky_inputs.filter(|_| changed && !flipped) {
        visual_context_values_changed = arena.with_visual_context_state_lent(|arena, state| {
            let mut values_changed = false;
            if let Some(tree) = state.tree.as_mut() {
                values_changed = crate::painting::visual_context::refresh::refresh_sticky_constraints(
                    &arena.paintable_rows(),
                    &state.scroll_state,
                    tree,
                    inputs,
                );
            }
            state.needs_to_refresh_scroll_state = true;
            values_changed
        });
    }
    RenderingPreparation {
        outcome: RenderingPreparationOutcome {
            requires_display_list_recording: changed || background_source_changed,
            requires_visual_context_update: flipped,
            visual_context_values_changed,
        },
        clamped_scroll_offsets,
    }
}

pub(crate) fn refresh_scroll_state(
    arena: &mut LayoutNodeArena,
    device_pixels_per_css_pixel: f64,
    device_viewport_size: IntSize,
) -> (Option<Vec<FloatPoint>>, CompositorScrollRefreshOutcome) {
    arena.settle_scrollable_overflow();
    arena.with_visual_context_state_lent(|arena, state| {
        let outcome = refresh_compositor_scroll_table(
            arena,
            state,
            CompositorScrollInputs {
                device_pixels_per_css_pixel,
                device_viewport_size,
            },
        );
        let snapshot = state.needs_to_refresh_scroll_state.then(|| {
            let snapshot = scroll_state_snapshot(&arena.paintable_rows(), state, device_pixels_per_css_pixel);
            state.needs_to_refresh_scroll_state = false;
            snapshot
        });
        // The published recording holds a window of the document, which no longer covers what the viewport shows with
        // the scrollers and the transforms where they are now: the next recording places it again.
        let window_no_longer_covers = arena
            .paint_state()
            .window_of_published_recording
            .as_ref()
            .zip(state.tree.as_deref())
            .is_some_and(|((window, tree_of_recording), tree)| {
                !crate::painting::record::window::still_covers(
                    window,
                    tree_of_recording,
                    tree,
                    device_viewport_size,
                    device_pixels_per_css_pixel,
                    state.scroll_state.own_offsets(),
                )
            });
        let outcome = CompositorScrollRefreshOutcome {
            requires_display_list_recording: outcome.requires_display_list_recording || window_no_longer_covers,
            ..outcome
        };
        (snapshot, outcome)
    })
}

/// The device scroll offsets of the nodes of `state`'s tree, refreshed from the rows where they may have moved.
fn scroll_state_snapshot(
    paintable_rows: &impl crate::painting::paintable_rows::PaintableRowsRead,
    state: &mut VisualContextState,
    device_pixels_per_css_pixel: f64,
) -> Vec<FloatPoint> {
    if state.needs_to_refresh_scroll_state {
        crate::painting::visual_context::refresh::refresh_scroll_state(paintable_rows, &mut state.scroll_state);
    }
    let mut snapshot = state.scroll_state.snapshot(device_pixels_per_css_pixel);
    // https://drafts.csswg.org/css-position/#sticky-pos
    if let Some(tree) = state.tree.as_deref() {
        tree.resolve_sticky_offsets_in_place(&mut snapshot);
    }
    snapshot
}

pub(crate) fn update_visual_viewport_transform(arena: &mut LayoutNodeArena, inputs: &FfiVisualContextTreeInputs) {
    let paint_state = arena.paint_state_mut();
    if let Some(tree) = &mut paint_state.visual_context.tree {
        std::sync::Arc::make_mut(tree).set_visual_viewport_transform(
            crate::painting::visual_context::node_values::visual_viewport_transform_data(inputs),
        );
    }
}

pub(crate) fn update_accumulated_visual_contexts(
    arena: &mut LayoutNodeArena,
    viewport: NodeSlotId,
    inputs: FfiVisualContextTreeInputs,
) -> VisualContextUpdateOutcome {
    arena.settle_scrollable_overflow();
    if !arena.paintable_row_is_populated(viewport) {
        return VisualContextUpdateOutcome::default();
    }
    let mut state = std::mem::take(&mut arena.paint_state_mut().visual_context);
    state.release_quarantined_slots_while_no_handle_is_retained();
    let trace_header = state.trace.as_mut().map(|trace| trace.begin_update());

    let mut scope = state.dirty_boxes.scope;
    if state.tree.is_none() {
        scope = VisualContextUpdateScope::FreshTree;
    }
    let asked_scope = scope;
    let viewport_overflow = arena
        .paintable_rows()
        .node_style_if_live(viewport)
        .map_or((0, 0), |style| (style.overflow_x(), style.overflow_y()));
    let viewport_overflow_changed =
        std::mem::replace(&mut state.last_viewport_overflow, viewport_overflow) != viewport_overflow;
    if viewport_overflow_changed {
        // The wheel targets of every hit-test item end at the viewport where it scrolls, which no box capture of the
        // last recording knows: none of its scroll metadata stands.
        arena.note_everything_paints_anew();
    }
    if state.last_tree_inputs.is_some_and(|last| {
        last.device_pixels_per_css_pixel != inputs.device_pixels_per_css_pixel || viewport_overflow_changed
    }) {
        scope = scope.max(VisualContextUpdateScope::EveryBox);
    }
    if state.tree.as_deref().is_some_and(|tree| tree.should_compact()) {
        scope = VisualContextUpdateScope::FreshTree;
    }
    let values_may_have_changed = scope != VisualContextUpdateScope::DirtyPath || !state.dirty_boxes.is_empty();

    while scope != VisualContextUpdateScope::FreshTree {
        let result = update_visual_context_tree(&mut arena.paintable_rows_mut(), viewport, inputs, scope, &mut state);
        match result {
            IncrementalUpdateResult::Applied(mut outcome) => {
                super::ffi::apply_walk_assignments(arena, &mut outcome);
                arena.resort_stacking_context_entries_flagged_for_resort();
                crate::painting::fragment_ownership::assign_fragment_ownership_for_pending_line_roots(arena);
                let performed_full_build = scope == VisualContextUpdateScope::EveryBox;
                if performed_full_build {
                    debug_assert_every_live_node_is_owned(
                        &arena.paintable_rows(),
                        state.tree.as_deref().expect("an applied walk keeps the tree"),
                        viewport,
                    );
                }
                state.dirty_boxes.clear();
                state.last_tree_inputs = Some(inputs);
                if let (Some(trace), Some(header)) = (state.trace.as_mut(), trace_header) {
                    trace.finish_update(header, asked_scope, scope, &outcome.delta, |slot| {
                        (arena.node_style_node(slot), slot == viewport)
                    });
                }
                let outcome = VisualContextUpdateOutcome {
                    performed_full_build,
                    structural_epoch_changed: outcome.delta.structural_epoch_changed,
                    requires_display_list_recording: outcome.delta.requires_display_list_recording,
                    values_may_have_changed,
                };
                arena.paint_state_mut().visual_context = state;
                return outcome;
            }
            IncrementalUpdateResult::NeedsFullBuild(fallback_scope) => {
                assert!(fallback_scope > scope, "a fallback widens the update scope");
                scope = fallback_scope;
            }
        }
    }

    let outcome = fresh_visual_context_tree_build(arena, viewport, inputs, &mut state);
    state.last_tree_inputs = Some(inputs);
    if let (Some(trace), Some(header)) = (state.trace.as_mut(), trace_header) {
        let delta = crate::painting::visual_context::delta::VisualContextTreeDelta {
            structural_epoch_changed: outcome.structural_epoch_changed,
            requires_display_list_recording: outcome.requires_display_list_recording,
            tombstoned_any_node: false,
        };
        trace.finish_update(header, asked_scope, VisualContextUpdateScope::FreshTree, &delta, |_| {
            (None, false)
        });
    }
    arena.paint_state_mut().visual_context = state;
    outcome
}

fn fresh_visual_context_tree_build(
    arena: &mut LayoutNodeArena,
    viewport: NodeSlotId,
    inputs: crate::painting::host::FfiVisualContextTreeInputs,
    state: &mut VisualContextState,
) -> VisualContextUpdateOutcome {
    let mut fresh_tree = crate::painting::visual_context::build::create_fresh_tree_with_viewport_nodes(
        &arena.paintable_rows(),
        viewport,
        &inputs,
    );
    fresh_tree.viewport_assignment.node_identity = arena.unique_node_ids().id(viewport);
    {
        let mut paintable_rows = arena.paintable_rows_mut();
        paintable_rows.drop_all_visual_context_records();
        fresh_tree.viewport_assignment.apply(&mut paintable_rows);
    }
    state.tree = Some(std::sync::Arc::new(fresh_tree.tree));
    state.dirty_boxes.clear();
    let mut outcome = match update_visual_context_tree(
        &mut arena.paintable_rows_mut(),
        viewport,
        inputs,
        VisualContextUpdateScope::FreshTree,
        state,
    ) {
        IncrementalUpdateResult::Applied(outcome) => *outcome,
        IncrementalUpdateResult::NeedsFullBuild(_) => {
            unreachable!("a fresh tree walk has a tree and a viewport record")
        }
    };
    arena.note_everything_paints_anew();
    super::ffi::apply_walk_assignments(arena, &mut outcome);
    arena.rebuild_all_stacking_context_entries_from_records(viewport);
    arena.take_line_roots_needing_fragment_ownership();
    crate::painting::fragment_ownership::assign_fragment_ownership(&mut arena.paintable_rows_mut(), viewport);
    state.quarantined_slots_are_releasable = false;
    debug_assert_every_live_node_is_owned(
        &arena.paintable_rows(),
        state.tree.as_deref().expect("a fresh tree walk keeps the tree"),
        viewport,
    );
    VisualContextUpdateOutcome {
        performed_full_build: true,
        structural_epoch_changed: true,
        requires_display_list_recording: true,
        values_may_have_changed: true,
    }
}

/// An SVG paint resource of an enrolled row the host resolves from the DOM.
pub(crate) enum SvgPaintResourceRequest {
    PaintServer {
        slot: NodeSlotId,
        kind: SvgPaintResourceKind,
    },
    /// A filter list, with the `url()` of each filter that names an SVG filter.
    Filter {
        slot: NodeSlotId,
        kind: SvgPaintResourceKind,
        urls: Vec<crate::css::style_value::RetainedStyleValueData>,
    },
}

/// What the host resolved of an [`SvgPaintResourceRequest`].
pub(crate) enum ResolvedSvgPaintResource {
    PaintServer {
        slot: NodeSlotId,
        kind: SvgPaintResourceKind,
        published: PublishedSvgPaintServer,
    },
    Filter {
        slot: NodeSlotId,
        kind: SvgPaintResourceKind,
        published: PublishedSvgFilter,
    },
}

/// What the host resolves of the enrolled SVG paint resources, if they changed since they were
/// resolved last. A row that went away, or whose filters name no SVG filter any more, leaves them.
pub(crate) fn svg_paint_resource_requests(arena: &mut LayoutNodeArena) -> Option<Vec<SvgPaintResourceRequest>> {
    if !arena.svg_paint_resources_mut().take_needs_sync() {
        return None;
    }
    let mut requests = Vec::new();
    for (slot, kind) in arena.svg_paint_resources().enrolled_entries() {
        let Some(style) = arena.node_style_if_live(slot) else {
            arena.svg_paint_resources_mut().forget_slot(slot);
            continue;
        };
        if matches!(kind, SvgPaintResourceKind::Fill | SvgPaintResourceKind::Stroke) {
            requests.push(SvgPaintResourceRequest::PaintServer { slot, kind });
            continue;
        }
        let effects = style.effects();
        let filter_list = match kind {
            SvgPaintResourceKind::Filter => &effects.filter,
            SvgPaintResourceKind::BackdropFilter => &effects.backdrop_filter,
            SvgPaintResourceKind::Fill | SvgPaintResourceKind::Stroke => unreachable!(),
        };
        if !crate::painting::css_filter::contains_url(filter_list) {
            arena.svg_paint_resources_mut().withdraw(slot, kind);
            continue;
        }
        let urls = filter_list
            .operations
            .as_slice()
            .iter()
            .filter(|operation| operation.kind == crate::painting::css_filter::FILTER_KIND_URL)
            .map(|operation| {
                // SAFETY: The row's style holds the value live; the request holds a reference of its
                // own, as the host may restyle the row while it resolves.
                unsafe {
                    crate::css::style_value::RetainedStyleValueData::from_retained_optional_pointer(
                        crate::css::style_value::retain_style_value(operation.url_value.pointer.cast()),
                    )
                }
            })
            .collect();
        requests.push(SvgPaintResourceRequest::Filter { slot, kind, urls });
    }
    Some(requests)
}

/// Publishes what the host resolved of the enrolled SVG paint resources, and answers whether any
/// changed.
pub(crate) fn publish_resolved_svg_paint_resources(
    arena: &mut LayoutNodeArena,
    resolved: Vec<ResolvedSvgPaintResource>,
) -> bool {
    use crate::painting::record::change_ticks::RowPaintChange;
    let mut any_changed = false;
    for resolved in resolved {
        match resolved {
            ResolvedSvgPaintResource::PaintServer { slot, kind, published } => {
                if arena.slot_is_live(slot)
                    && arena
                        .svg_paint_resources_mut()
                        .publish_paint_server(slot, kind, published)
                {
                    any_changed = true;
                    arena.note_paint_change(slot, RowPaintChange::DRAWING);
                }
            }
            ResolvedSvgPaintResource::Filter { slot, kind, published } => {
                if !arena.slot_is_live(slot) || !arena.svg_paint_resources_mut().publish_filter(slot, kind, published) {
                    continue;
                }
                any_changed = true;
                if arena.paintable_row_is_populated(slot) {
                    arena.note_visual_context_box_dirty(
                        slot,
                        crate::painting::visual_context::dirty::VisualContextBoxDirtyKind::StyleValueChange,
                    );
                    arena.note_paint_change(slot, RowPaintChange::DRAWING);
                }
            }
        }
    }
    any_changed
}