use std::num::NonZeroUsize;
use crate::css::{
AutomaticBlockSizeTraversal, ClampContinuation, ComputedStyle, LineLimitTraversal, PageBreak,
RemainingLineSlots,
};
use crate::document::paint::geometry::{PaintPoint, PaintRect, PaintSize};
use crate::layout::block::flow::fragmentation::FirstInFlowChildState;
use crate::layout::{
BlockEndMarginCollapse, BlockMarginCollapseBoundary, FirstFormattedLineState, FloatRunState,
LayoutLength, LayoutSnapshot, PendingAdjoiningMargin,
style_establishes_multicol_formatting_context,
};
use crate::units::{ContentBoxLength, SemanticLengthExt, content_box_pt, layout_pt};
pub(in crate::layout) struct AutomaticBlockSizeReplayState {
pub(in crate::layout) snapshot: LayoutSnapshot,
pub(in crate::layout) previous_flow_bottom_margin: Option<PendingAdjoiningMargin>,
pub(in crate::layout) seen_flow_child: FirstInFlowChildState,
pub(in crate::layout) trim_block_start_adjoining_margins: bool,
pub(in crate::layout) collapsed_end_margin: bool,
pub(in crate::layout) pending_end_margin_collapse: Option<BlockEndMarginCollapse>,
pub(in crate::layout) previous_child_page_end: Option<Option<String>>,
pub(in crate::layout) float_run: FloatRunState,
pub(in crate::layout) previous_break_after: PageBreak,
pub(in crate::layout) first_formatted_line: FirstFormattedLineState,
pub(in crate::layout) traversal_state: BlockFlowChildTraversalState,
}
pub(in crate::layout) struct DomAutomaticBlockSizeReplayCheckpoint {
pub(in crate::layout) state: AutomaticBlockSizeReplayState,
pub(in crate::layout) child_node_index: usize,
pub(in crate::layout) element_index: usize,
}
pub(in crate::layout) struct FormattingBoxAutomaticBlockSizeReplayCheckpoint {
pub(in crate::layout) state: AutomaticBlockSizeReplayState,
pub(in crate::layout) child_box_index: usize,
}
#[derive(Debug, Clone, Copy, Default)]
pub(in crate::layout) struct ChildFlowTraversalOutcome {
pub(in crate::layout) pending_end_margin_collapse: Option<BlockEndMarginCollapse>,
pub(in crate::layout) collapsed_start_margin_offset: LayoutLength,
pub(in crate::layout) adjoining_margin_set_boundary: BlockMarginCollapseBoundary,
pub(in crate::layout) rendered_legend: Option<RenderedLegendGeometry>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct RenderedLegendGeometry {
pub(in crate::layout) border_box: PaintRect,
pub(in crate::layout) margin_box: PaintRect,
pub(in crate::layout) source_fragmentainer: usize,
}
impl RenderedLegendGeometry {
pub(in crate::layout) fn from_static_border_box(
border_box: PaintRect,
margins: crate::css::Edges,
source_fragmentainer: usize,
) -> Self {
let margin_box = PaintRect::new(
PaintPoint::new(
border_box.origin.x - margins.left,
border_box.origin.y - margins.bottom,
),
PaintSize::new(
border_box.size.width + margins.left + margins.right,
border_box.size.height + margins.top + margins.bottom,
),
);
Self {
border_box,
margin_box,
source_fragmentainer,
}
}
pub(in crate::layout) fn border_exclusion(
self,
fieldset_border_box: PaintRect,
source_fragmentainer: usize,
) -> Option<RenderedLegendBorderExclusion> {
if self.source_fragmentainer != source_fragmentainer {
return None;
}
let hole = self.margin_box.intersection(&fieldset_border_box)?;
if hole.size.width >= fieldset_border_box.size.width - 0.01
|| hole.size.height >= fieldset_border_box.size.height - 0.01
{
return None;
}
let mut visible_regions = Vec::with_capacity(4);
let push = |regions: &mut Vec<PaintRect>, x, y, width, height| {
if width > 0.0 && height > 0.0 {
regions.push(PaintRect::new(
PaintPoint::new(x, y),
PaintSize::new(width, height),
));
}
};
push(
&mut visible_regions,
fieldset_border_box.min_x(),
fieldset_border_box.min_y(),
hole.min_x() - fieldset_border_box.min_x(),
fieldset_border_box.size.height,
);
push(
&mut visible_regions,
hole.max_x(),
fieldset_border_box.min_y(),
fieldset_border_box.max_x() - hole.max_x(),
fieldset_border_box.size.height,
);
push(
&mut visible_regions,
hole.min_x(),
fieldset_border_box.min_y(),
hole.size.width,
hole.min_y() - fieldset_border_box.min_y(),
);
push(
&mut visible_regions,
hole.min_x(),
hole.max_y(),
hole.size.width,
fieldset_border_box.max_y() - hole.max_y(),
);
(!visible_regions.is_empty()).then_some(RenderedLegendBorderExclusion { visible_regions })
}
}
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct RenderedLegendBorderExclusion {
pub(in crate::layout) visible_regions: Vec<PaintRect>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) struct DiscardSourcePrefix(NonZeroUsize);
impl DiscardSourcePrefix {
pub(in crate::layout) fn child_count(self) -> usize {
self.0.get()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) struct DiscardRegionLimit(NonZeroUsize);
impl DiscardRegionLimit {
pub(in crate::layout) const fn new(value: NonZeroUsize) -> Self {
Self(value)
}
fn reached_by(self, completed_local_regions: usize) -> bool {
completed_local_regions >= self.0.get()
}
}
#[derive(Clone)]
pub(in crate::layout) struct BlockFlowChildTraversalState {
source: Option<LineLimitTraversal>,
remaining: Option<RemainingLineSlots>,
automatic: Option<AutomaticBlockSizeTraversal>,
local_continuation_cutoff: bool,
discard_region_limit: Option<DiscardRegionLimit>,
discard_region_traversal: Option<crate::css::DiscardRegionTraversal>,
descendant_clamp_line_slots: usize,
}
pub(in crate::layout) fn direct_automatic_block_size_constraint(
style: &ComputedStyle,
) -> Option<ContentBoxLength> {
let applies = match style.used_continuation() {
crate::css::UsedContinuation::LineClamp(container) => {
matches!(
container.cutoff,
crate::css::ClampPointRule::AutomaticBlockSize
)
}
crate::css::UsedContinuation::Discard(container) => {
matches!(container.max_lines, crate::css::MaxLines::None)
}
crate::css::UsedContinuation::Ordinary => false,
};
if !applies {
return None;
}
let mut height = style.box_values.height.clone();
let mut min_height = style.box_values.min_height.clone();
let mut max_height = style.box_values.max_height.clone();
let line_height = layout_pt(style.line_height);
height.resolve_line_height_relative_lengths(line_height);
min_height.resolve_line_height_relative_lengths(line_height);
max_height.resolve_line_height_relative_lengths(line_height);
let upper = height
.length_if_no_percent()
.into_iter()
.chain(max_height.length_if_no_percent())
.reduce(f32::min)?;
let used = min_height
.length_if_no_percent()
.map_or(upper, |minimum| upper.max(minimum));
Some(content_box_pt(used.max(0.0)))
}
impl BlockFlowChildTraversalState {
pub(in crate::layout) fn continuation_for_later_in_flow_source(
has_later_in_flow_source: bool,
) -> ClampContinuation {
if has_later_in_flow_source {
ClampContinuation::LaterInFlowContent
} else {
ClampContinuation::None
}
}
pub(in crate::layout) fn new(
style: &ComputedStyle,
automatic_constraint: Option<ContentBoxLength>,
) -> Self {
let source = (!style_establishes_multicol_formatting_context(style))
.then(|| {
style.line_limit_traversal.clone().or_else(|| {
style
.line_clamp_container()
.map(LineLimitTraversal::from_container)
})
})
.flatten();
let remaining = source.as_ref().map(|clamp| clamp.remaining);
let automatic = style.automatic_block_size_traversal.clone().or_else(|| {
(!style_establishes_multicol_formatting_context(style))
.then(|| match style.used_continuation() {
crate::css::UsedContinuation::LineClamp(container)
if matches!(
container.cutoff,
crate::css::ClampPointRule::AutomaticBlockSize
) =>
{
automatic_constraint.map(|remaining| {
AutomaticBlockSizeTraversal::new(remaining, container.marker.clone())
})
}
crate::css::UsedContinuation::Discard(container)
if matches!(container.max_lines, crate::css::MaxLines::None) =>
{
automatic_constraint.map(|remaining| {
AutomaticBlockSizeTraversal::new(remaining, container.marker.clone())
})
}
crate::css::UsedContinuation::Ordinary
| crate::css::UsedContinuation::LineClamp(_)
| crate::css::UsedContinuation::Discard(_) => None,
})
.flatten()
});
Self {
remaining,
source,
automatic,
local_continuation_cutoff: false,
discard_region_limit: None,
discard_region_traversal: matches!(
style.used_continuation(),
crate::css::UsedContinuation::Discard(_)
)
.then_some(crate::css::DiscardRegionTraversal::default()),
descendant_clamp_line_slots: 0,
}
}
pub(in crate::layout) fn is_exhausted(&self) -> bool {
self.local_continuation_cutoff
|| self.remaining == Some(RemainingLineSlots::Exhausted)
|| self
.automatic
.as_ref()
.is_some_and(AutomaticBlockSizeTraversal::is_exhausted)
}
pub(in crate::layout) fn mark_local_continuation_cutoff(&mut self) {
self.local_continuation_cutoff = true;
}
pub(in crate::layout) fn has_local_continuation_cutoff(&self) -> bool {
self.local_continuation_cutoff
}
pub(in crate::layout) fn capture_discard_source_prefix(&mut self, child_count: NonZeroUsize) {
self.mark_local_continuation_cutoff();
let Some(traversal) = self.discard_region_traversal.as_mut() else {
debug_assert!(
false,
"only a discard controller captures a local region break"
);
return;
};
traversal.capture_overflow(crate::css::RegionOverflowPoint::after_direct_children(
child_count,
));
}
pub(in crate::layout) fn capture_forced_discard_before_later_child(
&mut self,
later_child_index: usize,
) {
let Some(traversal) = self.discard_region_traversal.as_mut() else {
return;
};
let point = match later_child_index.checked_sub(1) {
Some(preceding_in_flow_child_index) => crate::css::ClampPoint::BetweenBlockSiblings(
crate::css::BlockClampPoint::after_in_flow_child(preceding_in_flow_child_index),
),
None => crate::css::ClampPoint::AtContainerStart,
};
traversal.capture_forced_after_lines(point);
}
pub(in crate::layout) fn discard_source_prefix(&self) -> Option<DiscardSourcePrefix> {
self.discard_region_traversal.and_then(|traversal| {
traversal.first_break().and_then(|break_| match break_ {
crate::css::CapturedRegionBreak::Overflow(point) => {
Some(DiscardSourcePrefix(point.retained_direct_children()))
}
crate::css::CapturedRegionBreak::ForcedAfterLines(
crate::css::ClampPoint::BetweenBlockSiblings(point),
) => {
let _ = point.preceding_in_flow_child_index();
None
}
crate::css::CapturedRegionBreak::ForcedAfterLines(
crate::css::ClampPoint::AtContainerStart
| crate::css::ClampPoint::AfterInlineLine(_),
) => None,
})
})
}
pub(in crate::layout) fn set_discard_region_limit(
&mut self,
limit: Option<DiscardRegionLimit>,
) {
self.discard_region_limit = limit;
}
pub(in crate::layout) fn has_reached_discard_region_limit(
&self,
completed_local_regions: usize,
) -> bool {
self.discard_region_limit
.is_some_and(|limit| limit.reached_by(completed_local_regions))
}
pub(in crate::layout) fn debit_inline_outcome(
&mut self,
outcome: crate::layout::inline_layout::InlineLayoutOutcome,
) {
self.debit_rendered_slots(outcome.clamp_line_slots);
self.debit_automatic_block_contribution(outcome.clamp_block_advance);
if outcome.has_local_continuation_cutoff {
self.mark_local_continuation_cutoff();
}
}
pub(in crate::layout) fn remaining_line_slots(&self) -> Option<RemainingLineSlots> {
self.remaining
}
pub(in crate::layout) fn has_active_clamp(&self) -> bool {
self.remaining.is_some() || self.automatic.is_some()
}
pub(in crate::layout) fn has_automatic_block_size_clamp(&self) -> bool {
self.automatic.is_some()
}
pub(in crate::layout) fn automatic_remaining(&self) -> Option<ContentBoxLength> {
self.automatic
.as_ref()
.map(AutomaticBlockSizeTraversal::remaining)
}
pub(in crate::layout) fn automatic_terminal_boundary_style(
&self,
style: &ComputedStyle,
) -> Option<ComputedStyle> {
let automatic = self.automatic.as_ref()?;
let mut boundary = style.clone();
boundary.automatic_block_size_traversal = None;
boundary.automatic_block_boundary_marker = Some(crate::css::AutomaticBlockBoundaryMarker(
automatic.marker().clone(),
));
Some(boundary)
}
pub(in crate::layout) fn admits_zero_height_automatic_child(
&self,
child_style: &ComputedStyle,
) -> bool {
self.remaining.is_none()
&& self
.automatic
.as_ref()
.is_some_and(AutomaticBlockSizeTraversal::is_exhausted)
&& child_style
.box_values
.height
.length_if_no_percent()
.is_some_and(|height| height.abs() <= 0.01)
}
pub(in crate::layout) fn capture_avoid_replay(&self) -> Option<RemainingLineSlots> {
self.remaining
}
pub(in crate::layout) fn restore_avoid_replay(
&mut self,
remaining: Option<RemainingLineSlots>,
) {
self.remaining = remaining;
}
pub(in crate::layout) fn debit(&mut self, slots: crate::css::PositiveLineCount) {
if let Some(remaining) = self.remaining {
self.remaining = Some(remaining.debit(slots));
}
}
pub(in crate::layout) fn debit_rendered_slots(&mut self, slots: usize) {
if let Some(slots) = crate::css::PositiveLineCount::from_rendered_slots(slots) {
self.debit(slots);
}
}
pub(in crate::layout) fn apply_to_with_continuation(
&self,
style: &mut ComputedStyle,
continuation: ClampContinuation,
) {
if let (Some(remaining), Some(clamp)) = (self.remaining, self.source.as_ref()) {
style.line_limit_traversal = Some(
clamp
.with_remaining(remaining)
.with_continuation(continuation),
);
}
if let Some(automatic) = self.automatic.as_ref() {
style.automatic_block_size_traversal = Some(automatic.clone());
}
}
pub(in crate::layout) fn reserve_automatic_child_non_content(
style: &mut ComputedStyle,
contribution: ContentBoxLength,
) {
debug_assert!(contribution.points() >= 0.0);
if let Some(automatic) = style.automatic_block_size_traversal.as_mut() {
automatic.debit(contribution);
}
}
pub(in crate::layout) fn require_automatic_terminal_marker_when_full(
style: &mut ComputedStyle,
) {
if let Some(automatic) = style.automatic_block_size_traversal.take() {
style.automatic_block_size_traversal = Some(automatic.with_terminal_marker_when_full());
}
}
pub(in crate::layout) fn apply_zero_height_automatic_boundary(
&self,
style: &mut ComputedStyle,
has_later_in_flow_source: bool,
) {
if self.admits_zero_height_automatic_child(style)
&& let Some(automatic) = self.automatic.as_ref()
{
style.automatic_block_size_traversal = None;
style.automatic_block_boundary_marker = has_later_in_flow_source
.then(|| crate::css::AutomaticBlockBoundaryMarker(automatic.marker().clone()));
}
}
pub(in crate::layout) fn debit_automatic_block_contribution(&mut self, used: ContentBoxLength) {
if let Some(automatic) = self.automatic.as_mut() {
automatic.debit(used);
}
}
#[cfg(test)]
pub(in crate::layout) fn apply_to(&self, style: &mut ComputedStyle) {
self.apply_to_with_continuation(style, ClampContinuation::None);
}
pub(in crate::layout) fn style_with_remaining(
&self,
style: &ComputedStyle,
) -> Option<ComputedStyle> {
self.style_with_remaining_and_continuation(style, ClampContinuation::None)
}
pub(in crate::layout) fn style_with_remaining_and_continuation(
&self,
style: &ComputedStyle,
continuation: ClampContinuation,
) -> Option<ComputedStyle> {
(self.remaining.is_some() || self.automatic.is_some()).then(|| {
let mut style = style.clone();
self.apply_to_with_continuation(&mut style, continuation);
style
})
}
pub(in crate::layout) fn record_descendant_clamp_line_slots(&mut self, slots: usize) {
self.descendant_clamp_line_slots += slots;
}
pub(in crate::layout) fn descendant_clamp_line_slots(&self) -> usize {
self.descendant_clamp_line_slots
}
}