Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
//! The FFI entry points of the parent module that mint a main thread token. The token's marker
//! can be made only here, and this module is private, so the parent's own code can neither mint
//! a token nor call an entry that does.
use super::*;
use crate::painting::host::FfiCaretAt;
use crate::painting::host::FfiVisualContextTreeInputs;
use crate::painting::paint_passes::{PassEffect, run as run_paint_pass};
crate::stage::main_thread_ffi_entries!();
/// Answers `read` from the rows of `host`'s document as of every write the host made, spending `wait`, with every
/// row's overflow measured, as input and chrome read boxes: scroll limits, wheel targets, scrollbars and snap areas.
fn read_measured_rows<R>(
host: &crate::render_state::DocumentHost,
wait: impl crate::render_state::RenderWait,
read: impl FnOnce(&crate::painting::paint_read::PaintSource<'_>) -> R,
) -> R {
host.read_rows(wait, true, read)
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_row_paintable_physical_resize_axes(
host: &crate::render_state::DocumentHost,
slot: NodeSlotId,
) -> FfiPhysicalResizeAxes {
let axes = read_measured_rows(host, super::node_read(), |rows| {
crate::painting::chrome_geometry::physical_resize_axes(rows, slot)
});
FfiPhysicalResizeAxes {
horizontal: axes.horizontal,
vertical: axes.vertical,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_row_paintable_minimum_scroll_offset(
host: &crate::render_state::DocumentHost,
slot: NodeSlotId,
out: &mut FfiCssPixelPoint,
) {
*out = {
read_measured_rows(host, super::node_read(), |rows| {
crate::painting::chrome_geometry::minimum_scroll_offset(rows, slot)
})
}
.into();
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_row_paintable_maximum_scroll_offset(
host: &crate::render_state::DocumentHost,
slot: NodeSlotId,
out: &mut FfiCssPixelPoint,
) {
*out = {
read_measured_rows(host, super::node_read(), |rows| {
crate::painting::chrome_geometry::maximum_scroll_offset(rows, slot)
})
}
.into();
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_row_paintable_wheel_scrollable_axes(
host: &crate::render_state::DocumentHost,
slot: NodeSlotId,
) -> FfiPhysicalResizeAxes {
let axes = read_measured_rows(host, super::node_read(), |rows| {
crate::painting::chrome_geometry::wheel_scrollable_axes(rows, slot)
});
FfiPhysicalResizeAxes {
horizontal: axes.horizontal,
vertical: axes.vertical,
}
}
fn snap_container_geometry(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
) -> Option<libcompositing_rust::scrolling::scroll_snap_selection::SnapContainerGeometry> {
read_measured_rows(host, super::node_read(), |rows| {
crate::painting::scroll_snap::snap_container_geometry(rows, snap_container)
})
.map(Into::into)
}
fn snap_areas(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
) -> Vec<libcompositing_rust::scrolling::scroll_snap_selection::SnapAreaGeometry> {
read_arena(host, super::node_read(), snap_container, |arena, snap_container| {
let mut areas = Vec::new();
crate::painting::scroll_snap::for_each_snap_area(&arena.paintable_rows(), snap_container, |slot, mut area| {
// A re-snap right after layout runs ahead of the visual context tree that names the area's
// element, so the area is named by what the build stamped onto its row.
area.node_id = arena.unique_node_ids().id(slot);
areas.push(area.into());
});
areas
})
}
/// # Safety
///
/// `receive` must copy what it keeps of the destination synchronously.
unsafe fn receive_snap_destination(
destination: libcompositing_rust::scrolling::SnapDestination,
receiver: *mut c_void,
receive: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiSnapDestination<'_>),
) {
use crate::painting::host::{FfiSnapAreaIdentity, FfiSnapDestination};
let x: Vec<FfiSnapAreaIdentity> = destination.snapped_areas.x.into_iter().map(Into::into).collect();
let y: Vec<FfiSnapAreaIdentity> = destination.snapped_areas.y.into_iter().map(Into::into).collect();
let destination = FfiSnapDestination {
position: destination.position.into(),
snapped_x: destination.snapped_x,
snapped_y: destination.snapped_y,
evaluated_x: destination.evaluated_x,
evaluated_y: destination.evaluated_y,
snapped_areas_x: ak::Span::new(&x),
snapped_areas_y: ak::Span::new(&y),
};
// SAFETY: The caller copies what it keeps of the destination synchronously.
unsafe { receive(receiver, &destination) };
}
/// Answers false, without calling `receive`, for a box that snaps along none of the axes the scroll selects a snap
/// position in.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread. `receive` must copy what it keeps of the
/// destination synchronously.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_select_snap_destination(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
destination: FfiCssPixelPoint,
strategy: &crate::painting::host::FfiSnapSelectionStrategy,
receiver: *mut c_void,
receive: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiSnapDestination<'_>),
) -> bool {
use libcompositing_rust::scrolling::scroll_snap_selection::{axes_to_evaluate, select_snap_destination};
let Some(geometry) = snap_container_geometry(host, snap_container) else {
return false;
};
let strategy = strategy.into();
if axes_to_evaluate(geometry.axes, &strategy).is_empty() {
return false;
}
let destination = select_snap_destination(
&geometry,
&snap_areas(host, snap_container),
destination.into(),
&strategy,
);
// SAFETY: The caller copies what it keeps of the destination synchronously.
unsafe { receive_snap_destination(destination, receiver, receive) };
true
}
struct SnapAreaDomRelationsOfHost<'a>(&'a crate::painting::host::FfiSnapAreaDomRelations);
impl crate::painting::scroll_resnap::SnapAreaDomRelations for SnapAreaDomRelationsOfHost<'_> {
fn area_contains_focused_node(&self, area: libcompositing_rust::scrolling::SnapAreaIdentity) -> bool {
// SAFETY: The entry point's caller keeps the relation callbacks live for selection.
unsafe { (self.0.area_contains_focused_node)(self.0.context, area.into()) }
}
fn area_contains_targeted_element(&self, area: libcompositing_rust::scrolling::SnapAreaIdentity) -> bool {
// SAFETY: The entry point's caller keeps the relation callbacks live for selection.
unsafe { (self.0.area_contains_targeted_element)(self.0.context, area.into()) }
}
fn element_of_area_is_ancestor_of_element_of(
&self,
area: libcompositing_rust::scrolling::SnapAreaIdentity,
other_area: libcompositing_rust::scrolling::SnapAreaIdentity,
) -> bool {
// SAFETY: The entry point's caller keeps the relation callbacks live for selection.
unsafe { (self.0.element_of_area_is_ancestor_of_element_of)(self.0.context, area.into(), other_area.into()) }
}
}
/// Answers false, without calling `receive`, for a box that snaps along no axis.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread. The relation callbacks must stay live for
/// selection, and `receive` must copy what it keeps of the destination synchronously.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_select_resnap_destination(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
current_offset: FfiCssPixelPoint,
snapped_areas_x: ak::Span<'_, crate::painting::host::FfiSnapAreaIdentity>,
snapped_areas_y: ak::Span<'_, crate::painting::host::FfiSnapAreaIdentity>,
relations: &crate::painting::host::FfiSnapAreaDomRelations,
receiver: *mut c_void,
receive: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiSnapDestination<'_>),
) -> bool {
let Some(geometry) = snap_container_geometry(host, snap_container) else {
return false;
};
if geometry.axes.is_empty() {
return false;
}
let selection = libcompositing_rust::scrolling::SnappedAreas {
x: snapped_areas_x.as_slice().iter().copied().map(Into::into).collect(),
y: snapped_areas_y.as_slice().iter().copied().map(Into::into).collect(),
};
let destination = crate::painting::scroll_resnap::select_resnap_destination(
&geometry,
&snap_areas(host, snap_container),
current_offset.into(),
&selection,
&SnapAreaDomRelationsOfHost(relations),
);
// SAFETY: The caller copies what it keeps of the destination synchronously.
unsafe { receive_snap_destination(destination, receiver, receive) };
true
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_row_scroll_snapport_rect(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
scrollport: FfiCssPixelRect,
out: &mut FfiCssPixelRect,
) {
*out = {
read_measured_rows(host, super::node_read(), |rows| {
crate::painting::scroll_snap::scroll_snapport_rect(rows, snap_container, scrollport.into())
})
}
.into();
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_row_scroll_snap_axes(
host: &crate::render_state::DocumentHost,
snap_container: NodeSlotId,
) -> crate::painting::host::FfiSnapAxes {
read_measured_rows(host, super::node_read(), |rows| {
crate::painting::scroll_snap::snap_axes_of_scroll_container(rows, snap_container)
})
}
/// The box a scroll brings the caret at `offset` in the text of `text` into view in, which it scrolls to `*offset_out`, or
/// an invalid slot for none.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_scroll_target_for_text_position(
host: &crate::render_state::DocumentHost,
text: NodeSlotId,
offset: usize,
affinity_is_downstream: bool,
scroll_block_axis: bool,
offset_out: &mut FfiCssPixelPoint,
) -> NodeSlotId {
let target = {
read_arena(
host,
super::node_read(),
(text, offset, affinity_is_downstream, scroll_block_axis),
|arena, (text, offset, affinity_is_downstream, scroll_block_axis)| {
arena.settle_scrollable_overflow();
crate::painting::scroll_chain::scroll_target_for_text_position(
&arena.paintable_rows(),
text,
offset,
affinity_is_downstream,
scroll_block_axis,
)
},
)
};
let Some((container, scroll_offset)) = target else {
return NodeSlotId::INVALID;
};
*offset_out = scroll_offset.into();
container
}
#[unsafe(no_mangle)]
pub extern "C" fn render_state_box_ending_scroll_chain(
host: &crate::render_state::DocumentHost,
start: NodeSlotId,
delta_x: f64,
delta_y: f64,
) -> NodeSlotId {
read_arena(
host,
node_read(),
(start, delta_x, delta_y),
|arena, (start, delta_x, delta_y)| {
crate::painting::scroll_chain::box_ending_scroll_chain(&arena.paintable_rows(), start, delta_x, delta_y)
},
)
}
#[unsafe(no_mangle)]
pub extern "C" fn render_state_first_wheel_scrollable_box_in_containing_block_chain(
host: &crate::render_state::DocumentHost,
start: NodeSlotId,
) -> NodeSlotId {
read_arena(host, node_read(), start, |arena, start| {
arena.settle_scrollable_overflow();
crate::painting::scroll_chain::first_wheel_scrollable_box_in_containing_block_chain(
&arena.paintable_rows(),
start,
)
})
}
/// Brings the paint and hit testing properties of `host`'s document up to date, for an entry of this module that hands
/// the host what they are prepared into.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread, as the calling entry's contract requires.
unsafe fn prepare_paint_properties(host: &crate::render_state::DocumentHost, read: &crate::render_state::BegunRead) {
// SAFETY: Guaranteed by the caller.
let main_thread = unsafe { main_thread(host) };
crate::painting::paint_passes::prepare_paint_properties(&main_thread, host, read);
}
/// Whether the visual context tree of `host`'s document, prepared up to date, changed since a frame last took it to the
/// compositor, which the caller's frame now does.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_take_visual_context_tree_compositor_update(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
) -> bool {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
host.paint_preparation()
.visual_context_tree_needs_compositor_update
.replace(false)
}
#[unsafe(no_mangle)]
pub extern "C" fn render_state_update_visual_viewport_transform(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
inputs: FfiVisualContextTreeInputs,
) {
run_paint_pass(read, host, PassEffect::StalesPaintPreparation, |arena| {
crate::painting::paint_passes::update_visual_viewport_transform(arena, &inputs);
});
host.paint_preparation()
.visual_context_tree_needs_compositor_update
.set(true);
}
/// Starts an update pass of the compositor animations of `host`'s document, with none published.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_begin_compositor_animation_update(host: &crate::render_state::DocumentHost) {
host.begin_compositor_animation_update();
}
/// Ends the current update pass of the compositor animations of `host`'s document, and gives the visual context tree,
/// prepared up to date, what its effects published where `publish_pending`, or none.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_publish_compositor_animations(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
publish_pending: bool,
) -> crate::painting::host::FfiCompositorAnimationPublishOutcome {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
let mut animations = host.take_compositor_animations();
if !publish_pending {
animations.clear();
}
let outcome = run_paint_pass(read, host, PassEffect::KeepsPaintPreparation, |arena| {
crate::painting::visual_context::publish_compositor_animations(
&mut arena.paint_state_mut().visual_context,
animations,
)
});
if outcome.published {
host.paint_preparation()
.visual_context_tree_needs_compositor_update
.set(true);
}
outcome
}
/// The visual context tree of `host`'s document, prepared up to date.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
pub(crate) unsafe fn main_visual_context_tree(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
) -> Option<std::sync::Arc<crate::painting::visual_context::VisualContextTree>> {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
if let Some(tree) = host.read_known_rows(|rows, _| rows.visual_context_tree.clone()) {
return tree;
}
read_arena(host, read, (), |arena, ()| {
arena.paint_state().visual_context.tree.clone()
})
}
/// Whether the scroll translations of the space `slot`'s box is painted in, in the visual context tree of `host`'s
/// document, prepared up to date, and the origins drawn in that space round to whole device pixels: no transform but
/// identities lies above it.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_translations_snap_to_device_pixels(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
slot: NodeSlotId,
) -> bool {
// NB: Preparing the tree can move the box's visual context to other nodes, so the box's space is read after.
// SAFETY: Guaranteed by the caller.
let Some(tree) = (unsafe { main_visual_context_tree(host, read) }) else {
return false;
};
let spatial = host.read_rows(node_read(), false, |rows| {
rows.paintable_row_is_populated(slot)
.then(|| rows.paintable_data(slot).accumulated_visual_context.spatial)
});
spatial.is_some_and(|spatial| tree.translations_snap_to_device_pixels(spatial))
}
/// The structural epoch of the visual context tree of `host`'s document, prepared up to date.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_visual_context_tree_structural_epoch(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
) -> u64 {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
let known = host.read_known_rows(|rows, _| {
rows.visual_context_tree
.as_ref()
.map_or(0, |tree| tree.structural_epoch)
});
known.unwrap_or_else(|| {
read_arena(host, read, (), |arena, ()| {
let paint_state = arena.paint_state();
paint_state.visual_context.structural_epoch()
})
})
}
/// How far sticky positioning moved `paintable` from its normal position, in device pixels, as the scroll state of
/// `host`'s document, prepared up to date, resolved it. Answers false when the accumulated visual context tree holds no
/// sticky node for `paintable`.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_sticky_device_offset(
host: &crate::render_state::DocumentHost,
paintable: NodeSlotId,
out: &mut libgfx_rust::FloatPoint,
) -> bool {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, host.begun_read_of_held_node(super::node_read())) };
let sticky_node_index = read_arena(host, super::node_read(), paintable, |arena, paintable| {
let paint_state = arena.paint_state();
paint_state
.visual_context
.scroll_state
.states()
.iter()
.find(|state| state.is_sticky && state.paintable == paintable)
.map(|state| state.node_index)
});
let Some(sticky_node_index) = sticky_node_index else {
return false;
};
*out = host.scroll_state().device_offset_for_index(sticky_node_index);
true
}
/// Hands `append_line` each node of the prepared visual context tree the box in `slot` owns, as the tree dump describes
/// it: its kind (0 for spatial, 1 for clip, 2 for effect), its index and its description.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread, and `append_line` must copy the bytes synchronously.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_dump_box_visual_context_nodes(
host: &crate::render_state::DocumentHost,
slot: NodeSlotId,
context: *mut std::ffi::c_void,
append_line: unsafe extern "C" fn(*mut std::ffi::c_void, u8, u32, *const u8, usize),
) {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, host.begun_read_of_held_node(super::node_read())) };
let lines = read_arena(host, super::node_read(), slot, |arena, slot| {
use crate::painting::visual_context::dump::VisualContextTreeDump;
let Some(tree) = arena.paint_state().visual_context.tree.clone() else {
return Vec::new();
};
arena.with_paintable_visual_context_node_handles(slot, |handles| {
let spatial = handles
.spatial
.iter()
.map(|&index| (0, index.0, tree.dump_spatial_node(index)));
let clips = handles
.clip_handles()
.map(|index| (1, index.0, tree.dump_clip_node(index)));
let effects = handles
.effects
.iter()
.map(|&index| (2, index.0, tree.dump_effect_node(index)));
spatial.chain(clips).chain(effects).collect::<Vec<_>>()
})
});
for (kind, index, text) in lines {
// SAFETY: Guaranteed by the caller.
unsafe { append_line(context, kind, index, text.as_ptr(), text.len()) };
}
}
/// Brings the paint and hit testing properties of `host`'s document up to date, for a test.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_prepare_paint_properties_for_testing(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
) {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
}
/// Brings the paint and hit testing properties of `host`'s document up to date before the document hit tests.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_prepare_paint_properties_before_hit_test(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
) {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
}
/// Where the stacking context structure below the viewport of `host`'s document differs from what paint preparation
/// recorded, handed to `consume` unless it does not.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread, and `consume` must copy the bytes synchronously.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_stacking_context_structure_verification_report(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
viewport: NodeSlotId,
context: *mut c_void,
consume: unsafe extern "C" fn(*mut c_void, *const u8, usize),
) {
// SAFETY: Guaranteed by the caller.
unsafe { prepare_paint_properties(host, read) };
let report = read_arena(host, read, viewport, |arena, viewport| {
crate::painting::stacking_context::verify::verification_report(arena, viewport)
});
if !report.is_empty() {
// SAFETY: Guaranteed by the caller.
unsafe { consume(context, report.as_ptr(), report.len()) };
}
}
/// # Safety
///
/// `host` must be a live document host, on its document's thread; the callbacks in `publish` are called
/// synchronously with their context while the recording's resources are live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_publish_recording(
host: &crate::render_state::DocumentHost,
publish: crate::painting::host::FfiRecordingPublishCallbacks,
) {
// SAFETY: Guaranteed by the entry point's contract.
let main_thread = unsafe { main_thread(host) };
let mut recording = host.recording();
if let Some(publication) = recording.take_publication() {
crate::painting::record::publish::publish_recording(host, publication, &main_thread, &publish);
}
}
/// # Safety
///
/// `host` must be a live document host, on its document's thread; `describe_node` and `append_text` are called
/// synchronously with `context`, and the slots handed to `describe_node` name the last recording's live paintables.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_take_recording_trace(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
context: *mut c_void,
describe_node: unsafe extern "C" fn(*mut c_void, NodeSlotId, *mut c_void),
append_text: unsafe extern "C" fn(*mut c_void, *const u8, usize),
) -> bool {
let Some(pending) = host.recording().take_pending_recording_trace() else {
return false;
};
let recording = read_arena(host, read, (), |arena, ()| arena.paint_state().last_recording.clone());
let Some(recording) = recording else {
return false;
};
let Some(log) = recording.capture_log.as_ref() else {
return false;
};
let mut name = |slot| {
if slot == pending.viewport {
return "@viewport".into();
}
let mut name = Vec::<u8>::new();
// SAFETY: the host copies the description synchronously into the sink.
unsafe { describe_node(context, slot, (&raw mut name).cast()) };
String::from_utf8(name).expect("trace label must be UTF-8")
};
let text = format!(
"recording (overlay={})\n{}",
pending.should_paint_overlay,
log.format(&mut name)
);
// SAFETY: the host copies the text synchronously.
unsafe { append_text(context, text.as_ptr(), text.len()) };
true
}
/// The recorder state of `host`'s document, for a recording to take, once the last recording was published.
fn take_recorder_for_recording(
host: &crate::render_state::DocumentHost,
_: &crate::render_state::BegunRead,
) -> crate::painting::record::recorder_state::RecorderState {
let mut recording = host.recording();
debug_assert!(
!recording.has_pending_recording() && !recording.has_recording_in_flight(),
"a recording must be published before the next one starts"
);
recording.discard_pending_recording();
recording.take_recorder()
}
/// What freezing the frame of a document's `viewport` for a recording with `inputs` reads.
fn frame_inputs(
viewport: NodeSlotId,
inputs: &crate::painting::host::FfiRecordingInputs,
recorder: &crate::painting::record::recorder_state::RecorderState,
) -> crate::painting::recording_slot::FrameInputs {
crate::painting::recording_slot::FrameInputs {
viewport,
css_viewport_rect: inputs.css_viewport_rect.into(),
publishes_recording: inputs.publishes_recording,
published_root_background_canvas_rect: recorder
.published_recording
.as_ref()
.map(|recording| recording.root_background_canvas_rect),
}
}
/// Records `host`'s document's viewport with `inputs` on the Paint thread, in step with the host, which publishes the
/// recording and presents nothing. Answers whether the viewport had a box to record.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread. Input arrays and byte buffers must be valid and
/// immutable for this call; fonts for enabled overlays must be live `Gfx::Font`s.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_record_display_list(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
viewport: NodeSlotId,
inputs: crate::painting::host::FfiRecordingInputs,
) -> FfiRecordingStart {
let recorder = take_recorder_for_recording(host, read);
let frame_inputs = frame_inputs(viewport, &inputs, &recorder);
// SAFETY: The host lends the input arrays and buffers for this call, and the inputs copy what they read of them.
let inputs = unsafe { inputs.recording_inputs() };
let Some(frame) = read_arena(
host,
read,
frame_inputs,
crate::painting::recording_slot::freeze_recording_frame,
) else {
host.recording().give_back_recorder(recorder);
return FfiRecordingStart::NothingToRecord;
};
let inputs = inputs.for_frame(frame.tree_inputs, frame.root_background_source);
let answer =
crate::painting::recording_slot::RecordingJob::new(frame, recorder, viewport, None).run_on_paint_thread(inputs);
host.recording().accept_recording_answer(answer);
FfiRecordingStart::Recorded
}
/// Commits the frame of `host`'s document as the rendering update leaves it to the render owner, with `recorder`, which
/// samples it beside the event loop at `timestamp`, the time of the document's timeline the update sampled its
/// animations at, and hands it to the Paint thread, which presents it as `seal` sealed it. The frame flies until the
/// host takes it in.
///
/// # Safety
///
/// `seal` must name a live presenter, and buffers of the sizes it gives.
unsafe fn commit_frame(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
recorder: crate::painting::record::recorder_state::RecorderState,
content: crate::render_state::CommittedContent,
held_for_testing: bool,
timestamp: f64,
seal: &crate::painting::presentation::FfiSeal,
) {
let publishes_recording = match &content {
crate::render_state::CommittedContent::Recording { frame_inputs, .. } => frame_inputs.publishes_recording,
crate::render_state::CommittedContent::Unrecorded { .. } => false,
};
// SAFETY: Guaranteed by the caller.
let presentation = unsafe {
crate::painting::presentation::Presentation::adopt(
seal,
&host.scroll_state(),
recorder.published_recording.clone(),
publishes_recording,
)
};
let commit = crate::render_state::CommittedFrame {
content,
recorder,
presentation,
timestamp,
held_for_testing,
};
let flight = host.commit_rendering_update(read, commit);
host.recording().fly(flight);
}
/// Commits the frame of `host`'s document as a recording of its viewport with `inputs` (see [`commit_frame`]).
///
/// # Safety
///
/// As for [`render_state_record_display_list`], and `seal` must be as [`commit_frame`] takes it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_commit_recorded_frame(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
viewport: NodeSlotId,
inputs: crate::painting::host::FfiRecordingInputs,
timestamp: f64,
seal: &crate::painting::presentation::FfiSeal,
) {
let recorder = take_recorder_for_recording(host, read);
let content = crate::render_state::CommittedContent::Recording {
frame_inputs: frame_inputs(viewport, &inputs, &recorder),
// SAFETY: The host lends the input arrays and buffers for this call, and the inputs copy what they read of them.
inputs: unsafe { inputs.recording_inputs() },
};
let held_for_testing = crate::painting::recording_slot::take_recording_hold_for_testing();
// SAFETY: Guaranteed by the caller.
unsafe { commit_frame(host, read, recorder, content, held_for_testing, timestamp, seal) };
}
/// Commits the frame of `host`'s document as one that keeps the display list the compositor has, and sends the render
/// state's visual context tree where `sends_visual_context_tree` says it changed (see [`commit_frame`]).
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread, and `seal` must be as [`commit_frame`] takes it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_commit_unrecorded_frame(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
sends_visual_context_tree: bool,
timestamp: f64,
seal: &crate::painting::presentation::FfiSeal,
) {
let recorder = take_recorder_for_recording(host, read);
let content = crate::render_state::CommittedContent::Unrecorded {
sends_visual_context_tree,
};
// SAFETY: Guaranteed by the caller.
unsafe { commit_frame(host, read, recorder, content, false, timestamp, seal) };
}
/// Renders the SVG images of the committed frame of `host`'s document that waits for them, with the callbacks in
/// `publish`, and hands the frame back to the Paint thread, which presents it with them. The frame flies again until the
/// host takes it in.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread, whose committed frame landed as
/// [`FfiRecordingLanding::NeedsVectorImages`]; the callbacks in `publish` are called synchronously with their context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_render_vector_images(
host: &crate::render_state::DocumentHost,
publish: crate::painting::host::FfiRecordingPublishCallbacks,
) {
// SAFETY: Guaranteed by the entry point's contract.
let main_thread = unsafe { main_thread(host) };
let (frame, recorder) = host
.recording()
.take_vector_image_frame()
.expect("a committed frame waits for its SVG images");
let display_lists =
crate::painting::record::publish::render_vector_images(frame.get().requests(), &main_thread, &publish);
let flight = crate::paint_stage::submit_presenting(frame, move |frame, presenting| {
frame.into_inner().present(recorder, &display_lists, presenting)
});
host.recording().fly(flight);
}
/// Holds the next recording that flies before it reads its frame, until the test releases it or the host waits for it.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_hold_next_recording_for_testing() {
crate::painting::recording_slot::hold_next_recording_for_testing();
}
/// Keeps the Render thread from claiming the next style update that flies, until the test releases it or the host waits
/// for it, which then takes it back.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_hold_next_style_flight_claim_for_testing() {
crate::painting::recording_slot::hold_next_style_flight_claim_for_testing();
}
/// Holds the next style update that flies before it reads anything, until the test releases it or the host waits
/// for it.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_hold_next_style_flight_for_testing() {
crate::painting::recording_slot::hold_next_style_flight_for_testing();
}
/// Lets the recording held for the test go.
#[unsafe(no_mangle)]
pub extern "C" fn render_state_release_held_recording_for_testing() {
crate::painting::recording_slot::release_held_recording_for_testing();
}
/// Takes the recording in flight of `host`'s document in where it has finished, and answers how it landed. The event
/// loop calls it between two tasks, so it never waits. A recording that landed writes whether presenting its frame sent
/// the compositor other scroll offsets than the frame before to `presented_other_scroll_offsets`.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread, and the event loop must call this between two tasks.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn render_state_take_finished_recording_in(
host: &crate::render_state::DocumentHost,
presented_other_scroll_offsets: &mut bool,
) -> FfiRecordingLanding {
let boundary = crate::render_state::TaskBoundary::at_event_loop_entry(&TAKES_FINISHED_RECORDING_IN);
let landing = host.recording().take_finished_recording_in(
&boundary,
|rows_version| landed_recording_stands(host, rows_version),
&mut |output, publishes_recording| {
take_in_presented_recording(host, output, publishes_recording);
},
);
recording_landing(landing, presented_other_scroll_offsets)
}
/// Waits for the recording in flight of `host`'s document and takes it in, and answers how it landed (see
/// [`render_state_take_finished_recording_in`]).
#[unsafe(no_mangle)]
pub extern "C" fn render_state_join_recording_in_flight(
host: &crate::render_state::DocumentHost,
presented_other_scroll_offsets: &mut bool,
) -> FfiRecordingLanding {
let landing = host.recording().join_recording_in_flight(
|rows_version| landed_recording_stands(host, rows_version),
&mut |output, publishes_recording| {
take_in_presented_recording(host, output, publishes_recording);
},
);
recording_landing(landing, presented_other_scroll_offsets)
}
/// Takes the output of a recording that presented itself in as the document's last.
fn take_in_presented_recording(
host: &crate::render_state::DocumentHost,
output: std::sync::Arc<crate::painting::record::RecordingOutput>,
publishes_recording: bool,
) {
host.queue_change(crate::render_state::ArenaChange::Paint(
crate::painting::paint_changes::PaintChange::TakeInRecording {
output,
publishes_recording,
},
));
}
/// Answers how a recording landed, and writes what the presentation it gave back presented to
/// `presented_other_scroll_offsets`.
fn recording_landing(
landing: crate::painting::recording_slot::RecordingLanding,
presentation: &mut bool,
) -> FfiRecordingLanding {
use crate::painting::recording_slot::RecordingLanding;
match landing {
RecordingLanding::NoneInFlight => FfiRecordingLanding::NoneInFlight,
RecordingLanding::StillInFlight => FfiRecordingLanding::StillInFlight,
RecordingLanding::Landed(given_back) => {
give_back(given_back, presentation);
FfiRecordingLanding::Landed
}
RecordingLanding::LandedBehindRows(given_back) => {
give_back(given_back, presentation);
FfiRecordingLanding::LandedBehindRows
}
RecordingLanding::NothingRecorded(given_back) => {
give_back(given_back, presentation);
FfiRecordingLanding::NothingRecorded
}
RecordingLanding::PresentedUnrecorded(given_back) => {
give_back(given_back, presentation);
FfiRecordingLanding::PresentedUnrecorded
}
RecordingLanding::NeedsVectorImages => FfiRecordingLanding::NeedsVectorImages,
}
}
/// Writes whether the presentation a recording gave back, if any, sent the compositor other scroll offsets than the
/// frame before to `presented_other_scroll_offsets`.
fn give_back(
given_back: Option<crate::painting::presentation::Presentation>,
presented_other_scroll_offsets: &mut bool,
) {
*presented_other_scroll_offsets =
given_back.is_some_and(|presentation| presentation.presented_other_scroll_offsets());
}
/// Whether the rows of `host`'s document are still at `version`, so that a recording that landed with a frame frozen
/// there shows what a hit test of the rows finds. The recording dropped its frame and the lease it held, so the style
/// engine frees what it kept for that lease here too, however idle the document stays.
fn landed_recording_stands(host: &crate::render_state::DocumentHost, version: crate::layout::RowsVersion) -> bool {
// A frame in flight, or a round that flew and is not paid yet, writes the rows, which then stand for no recording
// made before it.
let Some(here) = host.layout_waits_for_no_frame() else {
return false;
};
host.ask(here, |state| {
let arena = state.arena_mut();
arena.with_style_engine(|engine| engine.free_style_records_kept_for_leases());
arena.rows_version() == version
})
}
/// `tree` with the compositor's animations sampled at the time the query reads them at, where it reads them so, kept in
/// `sampled`; otherwise `tree` itself.
fn tree_as_the_query_reads_it<'tree>(
tree: &'tree crate::painting::visual_context::VisualContextTree,
callbacks: &crate::painting::host::FfiHitTestQueryCallbacks,
sampled: &'tree mut Option<crate::painting::visual_context::VisualContextTree>,
) -> &'tree crate::painting::visual_context::VisualContextTree {
match callbacks.visual_animation_sample_time_ns() {
Some(sample_time_ns) if tree.has_visual_animations() => {
sampled.insert(tree.with_visual_animation_samples(sample_time_ns))
}
_ => tree,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn layout_hit_test_items_on_screen_generation(host: &crate::render_state::DocumentHost) -> u64 {
host.recording().hit_test_items_generation()
}
/// The DOM node a hit on the paintable dispatches events to.
#[unsafe(no_mangle)]
pub extern "C" fn layout_paintable_event_dispatch_target(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
slot: NodeSlotId,
) -> crate::painting::host::FfiNodeIdentity {
read_measured_rows(host, read, |rows| {
crate::painting::hit_test::resolve::event_dispatch_target_of_paintable(rows, slot)
})
}
/// Answers `query` about `point` through `answer`, from the rows as of every write the host made, with every row's
/// scrollable overflow and ink overflow measured, in `read`. A hit test paints nothing, so it walks the overlays a
/// frame paints.
fn with_point_query<R>(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
query: &crate::painting::host::FfiHitTestQuery,
point: FfiCssPixelPoint,
default: R,
answer: impl FnOnce(&crate::painting::paint_read::PaintSource<'_>, crate::painting::hit_test::walk::PointQuery<'_>) -> R,
) -> R {
let scroll_state = host.scroll_state();
let callbacks =
crate::painting::host::FfiHitTestQueryCallbacks::for_host_query(query, scroll_state.device_offsets());
host.read_rows_measured_for_hit_testing(read, |rows, source| {
let Some(tree) = rows.visual_context_tree.as_deref() else {
return default;
};
let mut sampled = None;
let tree = tree_as_the_query_reads_it(tree, &callbacks, &mut sampled);
let world = callbacks.build_world_transforms(tree);
let callbacks = &callbacks.with_world_transforms(&world);
answer(
source,
crate::painting::hit_test::walk::PointQuery {
tree,
callbacks,
viewport: rows.viewport,
paint_overlay: true,
point: point.into(),
},
)
})
}
fn ffi_point_hit(
source: &crate::painting::paint_read::PaintSource<'_>,
hit: &crate::painting::hit_test::walk::PointHit,
) -> crate::painting::host::FfiPointHit {
use crate::painting::paint_read::GeometryRead;
assert!(
source.paintable_row_is_populated(hit.item.paintable),
"a hit names a paintable that has a row"
);
crate::painting::host::FfiPointHit {
paintable: hit.item.paintable,
hit_node: hit.item.hit_node,
chrome_widget_kind: hit.item.chrome_widget_kind,
local: hit.local_point.into(),
resolved: crate::painting::hit_test::resolve::resolve_hit(source, &hit.item, hit.local_point),
}
}
/// Writes the topmost thing under `point` to `out` and answers whether there is one.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn layout_hit_test_topmost_hit(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
query: crate::painting::host::FfiHitTestQuery,
point: FfiCssPixelPoint,
out: &mut crate::painting::host::FfiPointHit,
) -> bool {
let hit = with_point_query(host, read, &query, point, None, |source, point_query| {
crate::painting::hit_test::walk::topmost_hit(source, point_query).map(|hit| ffi_point_hit(source, &hit))
});
match hit {
Some(hit) => {
*out = hit;
true
}
None => false,
}
}
/// Hands `visit` everything under `point`, topmost first.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread; the sink pointer must stay valid for this
/// synchronous call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn layout_hit_test_all_hits(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
query: crate::painting::host::FfiHitTestQuery,
point: FfiCssPixelPoint,
sink: *mut c_void,
visit: unsafe extern "C" fn(*mut c_void, &crate::painting::host::FfiPointHit),
) {
let hits = with_point_query(host, read, &query, point, Vec::new(), |source, point_query| {
crate::painting::hit_test::walk::all_hits(source, point_query)
.iter()
.map(|hit| ffi_point_hit(source, hit))
.collect()
});
for hit in &hits {
// SAFETY: The C++ sink consumes the hit synchronously.
unsafe { visit(sink, hit) };
}
}
/// The caret position at `point`, or where `constraint_scope` is a box, the one that box gives it.
///
/// # Safety
///
/// `host` must be a live document host, on its document's thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn layout_hit_test_caret_position_from_point(
host: &crate::render_state::DocumentHost,
read: &crate::render_state::BegunRead,
query: crate::painting::host::FfiHitTestQuery,
point: FfiCssPixelPoint,
constraint_scope: NodeSlotId,
out: &mut FfiCaretAt,
) {
*out = with_point_query(host, read, &query, point, None, |source, point_query| {
crate::painting::hit_test::caret::caret_position_from_point(source, point_query, constraint_scope)
})
.unwrap_or_else(FfiCaretAt::none);
}
/// The style-tree identity of the first `<area>` of the image's map, in tree order, whose shape
/// covers the point. Zero when the image has no map, or when no shape covers the point.
#[unsafe(no_mangle)]
pub extern "C" fn layout_image_map_area_for_point(
host: &crate::render_state::DocumentHost,
slot: NodeSlotId,
x: f32,
y: f32,
) -> u32 {
host.fresh_rows(super::node_read()).image_map_area_for_point(slot, x, y)
}