Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

perf(layout): share source lookup within geometry batches

ldm07b42fa6440a7
diff --git a/moli-layout/src/layout_tree/query.rs b/moli-layout/src/layout_tree/query.rs
index 891e53446..187e47302 100644
--- a/moli-layout/src/layout_tree/query.rs
+++ b/moli-layout/src/layout_tree/query.rs
@@ -1,6 +1,6 @@
//! Public geometry request/answer types and the batch dispatcher.
-use std::{fmt::Debug, hash::Hash, ops::Range};
+use std::{collections::HashMap, fmt::Debug, hash::Hash, ops::Range};
use crate::LayoutError;
@@ -205,14 +205,81 @@ where
batch: &LayoutQueryBatch<N>,
metrics: LayoutPassMetrics,
) -> LayoutAnswers<N> {
+ self.answer_queries_with(batch, metrics, |_| None)
+ }
+
+ /// Answers a batch while letting the renderer specialize queries such as
+ /// shadow-tree offsetParent visibility before their default is computed.
+ /// Source lookup belongs to this operation, never to the retained tree.
+ pub fn answer_queries_with(
+ &self,
+ batch: &LayoutQueryBatch<N>,
+ metrics: LayoutPassMetrics,
+ mut specialize: impl FnMut(&LayoutQuery<N>) -> Option<LayoutQueryAnswer<N>>,
+ ) -> LayoutAnswers<N> {
+ let mut outputs = HashMap::new();
+ // Tiny batches keep the allocation-free direct source lookup. Count
+ // eligible queries, including repeats of a source used by many ranges.
+ if batch
+ .queries
+ .iter()
+ .filter_map(LayoutQuery::fragment_source)
+ .take(4)
+ .count()
+ == 4
+ {
+ outputs.extend(
+ batch
+ .queries
+ .iter()
+ .filter_map(LayoutQuery::fragment_source)
+ .map(|source| (source, None)),
+ );
+ self.source_outputs(&mut outputs);
+ }
let answers = batch
.queries
.iter()
- .map(|query| self.answer_query(query))
+ .map(|query| {
+ if let Some(answer) = specialize(query) {
+ return answer;
+ }
+ if let Some(output) = query
+ .fragment_source()
+ .and_then(|source| outputs.get(&source))
+ {
+ return self.answer_fragment_query(query, output.as_ref());
+ }
+ self.answer_query(query)
+ })
.collect();
LayoutAnswers { answers, metrics }
}
+ fn answer_fragment_query(
+ &self,
+ query: &LayoutQuery<N>,
+ output: Option<&LayoutNodeOutput>,
+ ) -> LayoutQueryAnswer<N> {
+ match query {
+ LayoutQuery::BoxModel { .. } => LayoutQueryAnswer::BoxModel(
+ output.and_then(|output| self.box_model_for_output(output)),
+ ),
+ LayoutQuery::ClientRects { .. } => LayoutQueryAnswer::ClientRects(
+ output.map_or_else(Vec::new, |output| self.client_rects_for_output(output)),
+ ),
+ LayoutQuery::ContentQuads { .. } => LayoutQueryAnswer::ContentQuads(
+ output.map_or_else(Vec::new, |output| self.content_quads_for_output(output)),
+ ),
+ LayoutQuery::TextRangeRects { utf16_range, .. } => {
+ LayoutQueryAnswer::TextRangeRects(output.map_or_else(Vec::new, |output| {
+ self.text_range_rects_for_output(output, utf16_range.clone())
+ }))
+ }
+ _ => unreachable!("fragment-source query"),
+ }
+ }
+
/// Answers one query without allocating a batch. Consumers can specialize
/// selected queries without first computing and discarding their defaults.
pub fn answer_query(&self, query: &LayoutQuery<N>) -> LayoutQueryAnswer<N> {
@@ -272,3 +339,15 @@ where
}
}
}
+
+impl<N: Copy> LayoutQuery<N> {
+ fn fragment_source(&self) -> Option<N> {
+ match self {
+ Self::BoxModel { source }
+ | Self::ClientRects { source }
+ | Self::ContentQuads { source }
+ | Self::TextRangeRects { source, .. } => Some(*source),
+ _ => None,
+ }
+ }
+}
diff --git a/moli-layout/src/layout_tree/source_query.rs b/moli-layout/src/layout_tree/source_query.rs
index b81384bd0..efd44fca9 100644
--- a/moli-layout/src/layout_tree/source_query.rs
+++ b/moli-layout/src/layout_tree/source_query.rs
@@ -1,6 +1,6 @@
//! CSSOM box, range, element-metric, and source-provenance projections.
-use std::{fmt::Debug, hash::Hash, ops::Range};
+use std::{collections::HashMap, fmt::Debug, hash::Hash, ops::Range};
use crate::LayoutPosition;
@@ -14,6 +14,11 @@ use super::{
tree::{CssSizingBox, FrozenLayoutBox, FrozenLayoutTree},
};
+#[cfg(test)]
+thread_local! {
+ static SOURCE_OUTPUT_BOX_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
#[derive(Clone, Copy, Debug, PartialEq)]
struct InlineOffsetGeometry {
layout_origin_in_document: LayoutPoint,
@@ -33,6 +38,8 @@ where
let mut found = false;
let mut output = LayoutNodeOutput::default();
for layout_box in &self.boxes {
+ #[cfg(test)]
+ SOURCE_OUTPUT_BOX_VISITS.with(|count| count.set(count.get() + 1));
if layout_box.principal_source == Some(source) {
output.principal_box = Some(layout_box.id);
found = true;
@@ -57,6 +64,42 @@ where
found.then_some(output)
}
+ /// Builds provenance only for this operation's requested sources. Absent
+ /// sources remain explicit None entries; fragment and proxy order follow
+ /// the canonical vectors exactly as in the direct source query.
+ pub(super) fn source_outputs(&self, outputs: &mut HashMap<N, Option<LayoutNodeOutput>>) {
+ for layout_box in &self.boxes {
+ #[cfg(test)]
+ SOURCE_OUTPUT_BOX_VISITS.with(|count| count.set(count.get() + 1));
+ if let Some(output) = layout_box
+ .principal_source
+ .and_then(|source| outputs.get_mut(&source))
+ {
+ output.get_or_insert_default().principal_box = Some(layout_box.id);
+ }
+ if let Some(output) = layout_box
+ .geometry_source
+ .and_then(|source| outputs.get_mut(&source))
+ {
+ output.get_or_insert_default().fragments.extend(
+ layout_box.fragments.iter().copied().filter(|id| {
+ self.fragment(*id).is_some_and(|fragment| {
+ !matches!(fragment.kind, LayoutFragmentKind::Line { .. })
+ })
+ }),
+ );
+ }
+ }
+ for (source, box_id) in &self.scroll_proxy_links {
+ if let Some(output) = outputs.get_mut(source) {
+ output
+ .get_or_insert_default()
+ .scroll_proxy_boxes
+ .push(*box_id);
+ }
+ }
+ }
+
pub fn element_metrics_for_source(&self, source: N) -> Option<LayoutElementMetrics<N>> {
self.element_metrics_for_source_with_offset_parent_filter(source, |_| true)
}
@@ -283,7 +326,10 @@ where
}
pub fn box_model_for_source(&self, source: N) -> Option<LayoutBoxModel> {
- let output = self.source_output(source)?;
+ self.box_model_for_output(&self.source_output(source)?)
+ }
+
+ pub(super) fn box_model_for_output(&self, output: &LayoutNodeOutput) -> Option<LayoutBoxModel> {
let fragment_models = output
.fragments
.iter()
@@ -312,9 +358,11 @@ where
}
pub fn client_rects_for_source(&self, source: N) -> Vec<LayoutQuad> {
- let Some(output) = self.source_output(source) else {
- return Vec::new();
- };
+ self.source_output(source)
+ .map_or_else(Vec::new, |output| self.client_rects_for_output(&output))
+ }
+
+ pub(super) fn client_rects_for_output(&self, output: &LayoutNodeOutput) -> Vec<LayoutQuad> {
output
.fragments
.iter()
@@ -333,9 +381,11 @@ where
}
pub fn content_quads_for_source(&self, source: N) -> Vec<LayoutQuad> {
- let Some(output) = self.source_output(source) else {
- return Vec::new();
- };
+ self.source_output(source)
+ .map_or_else(Vec::new, |output| self.content_quads_for_output(&output))
+ }
+
+ pub(super) fn content_quads_for_output(&self, output: &LayoutNodeOutput) -> Vec<LayoutQuad> {
output
.fragments
.iter()
@@ -360,9 +410,16 @@ where
}
pub fn text_range_rects(&self, source: N, utf16_range: Range<usize>) -> Vec<LayoutQuad> {
- let Some(output) = self.source_output(source) else {
- return Vec::new();
- };
+ self.source_output(source).map_or_else(Vec::new, |output| {
+ self.text_range_rects_for_output(&output, utf16_range)
+ })
+ }
+
+ pub(super) fn text_range_rects_for_output(
+ &self,
+ output: &LayoutNodeOutput,
+ utf16_range: Range<usize>,
+ ) -> Vec<LayoutQuad> {
#[derive(Clone, Copy)]
struct SelectedTextRect {
box_id: LayoutOutputBoxId,
@@ -750,8 +807,7 @@ mod tests {
}
}
- #[test]
- fn inline_offset_geometry_skips_unprojectable_fragments_and_keeps_one_dimensional_bounds() {
+ fn inline_fragment_tree() -> FrozenLayoutTree<u8> {
let box_id = LayoutOutputBoxId::from_index(0);
let coordinate_space = LayoutCoordinateSpaceId::from_index(1);
let skipped_fragment = LayoutFragmentId::from_index(0);
@@ -792,7 +848,7 @@ mod tests {
scrollbar_corner: None,
scrollbar_colors: None,
};
- let tree = FrozenLayoutTree::new(
+ FrozenLayoutTree::new(
0_u8,
LayoutViewport::new(100, 100, 1.0),
LayoutPoint::ZERO,
@@ -838,7 +894,15 @@ mod tests {
identity_space(None),
Vec::new(),
Vec::new(),
- );
+ )
+ }
+
+ #[test]
+ fn inline_offset_geometry_skips_unprojectable_fragments_and_keeps_one_dimensional_bounds() {
+ let tree = inline_fragment_tree();
+ let box_id = LayoutOutputBoxId::from_index(0);
+ let skipped_fragment = LayoutFragmentId::from_index(0);
+ let valid_fragment = LayoutFragmentId::from_index(1);
let output = LayoutNodeOutput {
principal_box: Some(box_id),
fragments: vec![skipped_fragment, valid_fragment],
@@ -859,4 +923,86 @@ mod tests {
);
assert_eq!(geometry.size, LayoutSize::new(0.0, 5.0));
}
+ #[test]
+ fn batch_fragment_queries_scan_boxes_once_and_preserve_missing_sources() {
+ use crate::{LayoutFlushReason, LayoutQuery, LayoutQueryBatch};
+ let mut tree = inline_fragment_tree();
+ for source in 2..=64 {
+ let mut layout_box = tree.boxes[0].clone();
+ layout_box.geometry.id = LayoutOutputBoxId::from_index(tree.boxes.len());
+ layout_box.geometry.fragments.clear();
+ layout_box.geometry_source = Some(source);
+ layout_box.principal_source = Some(source);
+ tree.boxes.push(layout_box);
+ }
+ // Include proxy-only and missing sources as well as repeated queries.
+ tree.scroll_proxy_links.push((100, tree.boxes[0].id));
+ let queries = LayoutQueryBatch::new(
+ (0..=128)
+ .flat_map(|source| {
+ [
+ LayoutQuery::ClientRects { source },
+ LayoutQuery::ContentQuads { source },
+ LayoutQuery::BoxModel { source },
+ LayoutQuery::TextRangeRects {
+ source,
+ utf16_range: 0..4,
+ },
+ ]
+ })
+ .collect(),
+ );
+ SOURCE_OUTPUT_BOX_VISITS.with(|count| count.set(0));
+ let expected = queries
+ .queries
+ .iter()
+ .map(|query| tree.answer_query(query))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ SOURCE_OUTPUT_BOX_VISITS.with(std::cell::Cell::get),
+ tree.boxes.len() * queries.queries.len()
+ );
+ SOURCE_OUTPUT_BOX_VISITS.with(|count| count.set(0));
+ // The metrics are pass diagnostics, copied unchanged by query batches.
+ let metrics = crate::LayoutPassMetrics {
+ reason: LayoutFlushReason::Test,
+ elapsed: std::time::Duration::ZERO,
+ box_tree_elapsed: std::time::Duration::ZERO,
+ list_marker_elapsed: std::time::Duration::ZERO,
+ form_control_elapsed: std::time::Duration::ZERO,
+ inline_preparation_elapsed: std::time::Duration::ZERO,
+ numeric_layout_elapsed: std::time::Duration::ZERO,
+ numeric_first_pass_elapsed: std::time::Duration::ZERO,
+ numeric_followup_passes_elapsed: std::time::Duration::ZERO,
+ overflow_detection_elapsed: std::time::Duration::ZERO,
+ scrollbar_feedback_elapsed: std::time::Duration::ZERO,
+ embedded_frame_elapsed: std::time::Duration::ZERO,
+ projection_elapsed: std::time::Duration::ZERO,
+ numeric_layout_pass_count: 0,
+ numeric_feedback_invalidated_node_count: 0,
+ numeric_feedback_overflow_recomputed_node_count: 0,
+ box_count: 0,
+ fragment_count: 0,
+ paint_event_count: 0,
+ paint_culled_event_count: 0,
+ paint_text_line_count: 0,
+ paint_culled_text_line_count: 0,
+ paint_operation_count: 0,
+ fallback_count: 0,
+ };
+ let answers = tree.answer_queries(&queries, metrics);
+ assert_eq!(answers.answers, expected);
+ assert_eq!(
+ SOURCE_OUTPUT_BOX_VISITS.with(std::cell::Cell::get),
+ tree.boxes.len()
+ );
+ assert_eq!(answers.metrics, metrics);
+ SOURCE_OUTPUT_BOX_VISITS.with(|count| count.set(0));
+ let one = LayoutQueryBatch::new(vec![LayoutQuery::ClientRects { source: 1 }]);
+ tree.answer_queries(&one, metrics);
+ assert_eq!(
+ SOURCE_OUTPUT_BOX_VISITS.with(std::cell::Cell::get),
+ tree.boxes.len()
+ );
+ }
}
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index 408f34afe..19aae8a30 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -158,6 +158,43 @@ fn build_with_request(
build_layout_pass(source, styles, &mut DocumentLayoutServices::new(), request).unwrap()
}
+fn assert_fragment_batches_match_direct_queries(
+ output: &LayoutPassResult<usize>,
+ sources: std::ops::Range<usize>,
+) {
+ let queries = LayoutQueryBatch::new(
+ sources
+ .flat_map(|source| {
+ [
+ LayoutQuery::BoxModel { source },
+ LayoutQuery::ClientRects { source },
+ LayoutQuery::ContentQuads { source },
+ LayoutQuery::TextRangeRects {
+ source,
+ utf16_range: 0..2,
+ },
+ LayoutQuery::TextRangeRects {
+ source,
+ utf16_range: 1..1,
+ },
+ LayoutQuery::TextRangeRects {
+ source,
+ utf16_range: 2..usize::MAX,
+ },
+ ]
+ })
+ .collect(),
+ );
+ let expected = queries
+ .queries
+ .iter()
+ .map(|query| output.answer_query(query))
+ .collect::<Vec<_>>();
+ let answers = output.answer_queries(&queries);
+ assert_eq!(answers.answers, expected);
+ assert_eq!(answers.metrics, output.metrics);
+}
+
fn assert_close(actual: f32, expected: f32) {
assert!(
(actual - expected).abs() <= 0.05,
@@ -2509,6 +2546,7 @@ fn display_contents_has_no_css_box_but_can_scroll_its_rendered_contents_into_vie
.insert(2, resolved(LayoutDisplay::Inline, Style::default()));
let output = build(&source, &mut styles);
+ assert_fragment_batches_match_direct_queries(&output, 0..5);
let contents = output.source_output(1).expect("display: contents source");
assert!(contents.principal_box.is_none());
assert!(contents.fragments.is_empty());
@@ -2659,6 +2697,7 @@ fn split_inline_continuations_remain_mapped_to_the_originating_element() {
.insert(4, resolved(LayoutDisplay::Inline, Style::default()));
let output = build(&source, &mut styles);
+ assert_fragment_batches_match_direct_queries(&output, 0..7);
let rects = output.client_rects_for_source(1);
assert_eq!(rects.len(), 2, "{rects:?}");
let first = rects[0].bounding_rect();
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
index fce7d51a8..585ba3f31 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
@@ -364,13 +364,10 @@ impl JsContextHost {
document: DomHandle,
queries: &LayoutQueryBatch<DomHandle>,
) -> Result<LayoutAnswers<DomHandle>, LayoutError> {
- self.with_published_layout_for_document(document, |tree, metrics| LayoutAnswers {
- answers: queries
- .queries
- .iter()
- .map(|query| self.answer_layout_query(tree, query))
- .collect(),
- metrics,
+ self.with_published_layout_for_document(document, |tree, metrics| {
+ tree.answer_queries_with(queries, metrics, |query| {
+ self.specialize_layout_query(tree, query)
+ })
})
}
@@ -436,9 +433,18 @@ impl JsContextHost {
tree: &FrozenLayoutTree<DomHandle>,
query: &LayoutQuery<DomHandle>,
) -> LayoutQueryAnswer<DomHandle> {
+ self.specialize_layout_query(tree, query)
+ .unwrap_or_else(|| tree.answer_query(query))
+ }
+
+ fn specialize_layout_query(
+ &self,
+ tree: &FrozenLayoutTree<DomHandle>,
+ query: &LayoutQuery<DomHandle>,
+ ) -> Option<LayoutQueryAnswer<DomHandle>> {
// Geometry and its coordinate environment come from the same
// published frame, even after live viewport changes.
- match query {
+ Some(match query {
LayoutQuery::ElementMetrics { source } => LayoutQueryAnswer::ElementMetrics(
tree.element_metrics_for_source_with_offset_parent_filter(*source, |candidate| {
self.offset_parent_candidate_is_exposed(*source, candidate)
@@ -454,8 +460,8 @@ impl JsContextHost {
LayoutQuery::CaretPosition { point } if !tree.viewport.contains(*point) => {
LayoutQueryAnswer::CaretPosition(None)
}
- _ => tree.answer_query(query),
- }
+ _ => return None,
+ })
}
/// Blink exposes only offset-parent candidates whose TreeScope is one of