Skip to content

armgit / moli

Public Imported from GitHub
0

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

13.4 KB
Raw Blame
//! Public geometry request/answer types and the batch dispatcher.

use std::{collections::HashMap, fmt::Debug, hash::Hash, ops::Range};

use crate::LayoutError;

use super::{
    hit_test::{LayoutCaretPosition, LayoutHit},
    model::{
        LayoutBoxModel, LayoutFragmentId, LayoutOutputBoxId, LayoutPoint, LayoutQuad,
        LayoutResolvedGridTracks, LayoutSize, LayoutViewport,
    },
    pass_result::LayoutPassMetrics,
    tree::FrozenLayoutTree,
};

/// A short-lived source view derived from frozen box provenance.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LayoutNodeOutput {
    pub principal_box: Option<LayoutOutputBoxId>,
    pub fragments: Vec<LayoutFragmentId>,
    /// Direct generated boxes used only to resolve operations whose target is
    /// a `display: contents` source. They do not manufacture CSSOM rects for
    /// the box-suppressed element itself.
    pub scroll_proxy_boxes: Vec<LayoutOutputBoxId>,
}

/// Document-level dimensions returned from the unified output.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayoutDocumentMetrics {
    pub viewport: LayoutViewport,
    pub viewport_scroll: LayoutPoint,
    pub content_size: LayoutSize,
}

/// CSSOM View metrics for one source element.
///
/// Transformed quads use viewport CSS pixels and therefore include CSS
/// `zoom`. Offset, size, and scroll fields are untransformed and have the
/// queried box's absolute zoom removed, as required by CSSOM View. Root client
/// dimensions come directly from the layout viewport and are not adjusted a
/// second time.
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutElementMetrics<N> {
    pub offset_parent: Option<N>,
    pub offset_position: LayoutPoint,
    /// Border-box origin in viewport CSS pixels after layout placement and
    /// scrolling, but before authored CSS transforms.
    pub border_origin_in_viewport_ignoring_css_transforms: LayoutPoint,
    pub offset_size: LayoutSize,
    pub content_size: LayoutSize,
    pub client_size: LayoutSize,
    pub client_border: LayoutPoint,
    pub scroll_size: LayoutSize,
    pub scroll_offset: LayoutPoint,
    pub minimum_scroll_offset: LayoutPoint,
    pub maximum_scroll_offset: LayoutPoint,
    pub scrollport: LayoutQuad,
    pub scrollable_overflow: LayoutQuad,
    pub is_scroll_container: bool,
    pub allows_user_scroll_x: bool,
    pub allows_user_scroll_y: bool,
    pub clips_overflow: bool,
    pub visible: bool,
    pub pointer_events: bool,
}

/// One ResizeObserver box size in logical CSS pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LayoutResizeObserverSize {
    pub inline_size: f32,
    pub block_size: f32,
}

/// CSS-box ResizeObserver sizes projected wholly from one frozen principal box.
/// The physical content size is used for contentRect width/height. The logical
/// content and border pairs use the writing axes and effective zoom captured
/// with the geometry, independently of authored box-sizing. This owned answer
/// does not add state to the frozen tree or provide SVG bounding-box semantics.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LayoutResizeObserverMetrics {
    pub content_size: LayoutSize,
    pub content_box_size: LayoutResizeObserverSize,
    pub border_box_size: LayoutResizeObserverSize,
}

/// One scroll container on a target's layout ancestor chain.
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutScrollContainerMetrics<N> {
    pub source: N,
    pub metrics: LayoutElementMetrics<N>,
}

/// Geometry needed to run one `scrollIntoView` operation without retaining
/// layout state or forcing source-dependent follow-up passes.
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutScrollIntoViewGeometry<N> {
    pub target_rects: Vec<LayoutQuad>,
    /// Innermost to outermost, including the root scrolling element.
    pub scroll_containers: Vec<LayoutScrollContainerMetrics<N>>,
}

/// Owned inputs for one IntersectionObserver target/root pair.
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutIntersectionGeometry {
    pub target_rects: Vec<LayoutQuad>,
    pub root_rect: LayoutQuad,
    pub ancestor_clips: Vec<LayoutQuad>,
    pub target_has_layout: bool,
    pub target_visible: bool,
    pub root_clips_overflow: bool,
    pub root_is_layout_ancestor: bool,
}

/// One request in an explicit same-pass geometry batch.
#[derive(Clone, Debug, PartialEq)]
pub enum LayoutQuery<N> {
    DocumentMetrics,
    BoxModel {
        source: N,
    },
    ClientRects {
        source: N,
    },
    ContentQuads {
        source: N,
    },
    TextRangeRects {
        source: N,
        utf16_range: Range<usize>,
    },
    ElementMetrics {
        source: N,
    },
    /// Physical content dimensions and logical CSS content/border sizes for RO.
    ResizeObserverMetrics {
        source: N,
    },
    /// Used Grid row and column tracks for a principal Grid container.
    UsedGridTracks {
        source: N,
    },
    ScrollIntoViewGeometry {
        source: N,
    },
    IntersectionGeometry {
        target: N,
        root: Option<N>,
    },
    HitTest {
        point: LayoutPoint,
        ignore_pointer_events_none: bool,
    },
    HitTestAll {
        point: LayoutPoint,
        ignore_pointer_events_none: bool,
    },
    CaretPosition {
        point: LayoutPoint,
    },
    EventOffset {
        source: N,
        point: LayoutPoint,
    },
}

/// A high-level batch that must be answered from one full layout pass.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LayoutQueryBatch<N> {
    pub queries: Vec<LayoutQuery<N>>,
}

impl<N> LayoutQueryBatch<N> {
    pub fn new(queries: Vec<LayoutQuery<N>>) -> Self {
        Self { queries }
    }

    pub fn push(&mut self, query: LayoutQuery<N>) {
        self.queries.push(query);
    }
}

/// One answer corresponding to the same-index query in a batch.
#[derive(Clone, Debug, PartialEq)]
pub enum LayoutQueryAnswer<N> {
    DocumentMetrics(LayoutDocumentMetrics),
    BoxModel(Option<LayoutBoxModel>),
    ClientRects(Vec<LayoutQuad>),
    ContentQuads(Vec<LayoutQuad>),
    TextRangeRects(Vec<LayoutQuad>),
    ElementMetrics(Option<LayoutElementMetrics<N>>),
    ResizeObserverMetrics(Option<LayoutResizeObserverMetrics>),
    UsedGridTracks(Option<LayoutResolvedGridTracks>),
    ScrollIntoViewGeometry(Option<LayoutScrollIntoViewGeometry<N>>),
    IntersectionGeometry(Option<LayoutIntersectionGeometry>),
    HitTest(Option<LayoutHit<N>>),
    HitTestAll(Vec<LayoutHit<N>>),
    CaretPosition(Option<LayoutCaretPosition<N>>),
    EventOffset(Option<LayoutPoint>),
}

/// Minimal owned results derived from one frozen layout tree.
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutAnswers<N> {
    pub answers: Vec<LayoutQueryAnswer<N>>,
    pub metrics: LayoutPassMetrics,
}

/// Common real/mock geometry boundary used by renderer consumers.
pub trait GeometryProvider {
    type NodeId: Copy + Debug + Eq + Hash;

    /// Answers a batch from the provider's latest layout state.
    ///
    /// Reading never computes layout. Real-layout providers require a tree
    /// published by a screenshot or screencast frame.
    fn answer(
        &mut self,
        queries: &LayoutQueryBatch<Self::NodeId>,
    ) -> Result<LayoutAnswers<Self::NodeId>, LayoutError>;
}

impl<N> FrozenLayoutTree<N>
where
    N: Copy + Debug + Eq + Hash,
{
    pub fn answer_queries(
        &self,
        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| {
                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> {
        match query {
            LayoutQuery::DocumentMetrics => {
                LayoutQueryAnswer::DocumentMetrics(LayoutDocumentMetrics {
                    viewport: self.viewport,
                    viewport_scroll: self.viewport_scroll,
                    content_size: self.content_size,
                })
            }
            LayoutQuery::BoxModel { source } => {
                LayoutQueryAnswer::BoxModel(self.box_model_for_source(*source))
            }
            LayoutQuery::ClientRects { source } => {
                LayoutQueryAnswer::ClientRects(self.client_rects_for_source(*source))
            }
            LayoutQuery::ContentQuads { source } => {
                LayoutQueryAnswer::ContentQuads(self.content_quads_for_source(*source))
            }
            LayoutQuery::TextRangeRects {
                source,
                utf16_range,
            } => LayoutQueryAnswer::TextRangeRects(
                self.text_range_rects(*source, utf16_range.clone()),
            ),
            LayoutQuery::ElementMetrics { source } => {
                LayoutQueryAnswer::ElementMetrics(self.element_metrics_for_source(*source))
            }
            LayoutQuery::ResizeObserverMetrics { source } => {
                LayoutQueryAnswer::ResizeObserverMetrics(
                    self.resize_observer_metrics_for_source(*source),
                )
            }
            LayoutQuery::UsedGridTracks { source } => {
                LayoutQueryAnswer::UsedGridTracks(self.used_grid_tracks_for_source(*source))
            }
            LayoutQuery::ScrollIntoViewGeometry { source } => {
                LayoutQueryAnswer::ScrollIntoViewGeometry(
                    self.scroll_into_view_geometry_for_source(*source),
                )
            }
            LayoutQuery::IntersectionGeometry { target, root } => {
                LayoutQueryAnswer::IntersectionGeometry(self.intersection_geometry(*target, *root))
            }
            LayoutQuery::HitTest {
                point,
                ignore_pointer_events_none,
            } => LayoutQueryAnswer::HitTest(self.hit_test(*point, *ignore_pointer_events_none)),
            LayoutQuery::HitTestAll {
                point,
                ignore_pointer_events_none,
            } => LayoutQueryAnswer::HitTestAll(
                self.hit_test_all(*point, *ignore_pointer_events_none),
            ),
            LayoutQuery::CaretPosition { point } => {
                LayoutQueryAnswer::CaretPosition(self.caret_position(*point))
            }
            LayoutQuery::EventOffset { source, point } => {
                LayoutQueryAnswer::EventOffset(self.event_offset_for_source(*source, *point))
            }
        }
    }
}

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,
        }
    }
}