use crate::document::{BlockBox, BlockContent, BoxNavigation};
use crate::graphics::{BoxDecoration, BoxPaint, Rect};
use crate::layout::{
LayoutError,
breaks::Fragmentainer,
geometry::horizontal,
margin::MarginStrut,
multicol::{ColumnFlow, ColumnGeometry, MeasuredColumns, SpannerFragment},
};
use crate::style::{BreakBetween, Display, Style};
use crate::text::{Line, TextContext};
mod metrics;
pub(super) use metrics::{ItemMetrics, MetricsKey};
#[derive(Clone, Copy)]
pub(super) struct BlockSizing {
pub natural_height: f32,
edges: [f32; 2],
pub used_height: Option<f32>,
alignment: f32,
}
impl BlockSizing {
fn new(
natural_height: f32,
geometry: &crate::layout::geometry::HorizontalBox,
used_height: Option<f32>,
) -> Self {
Self {
natural_height,
edges: [
geometry.padding[0] + geometry.border[0],
geometry.padding[2] + geometry.border[2],
],
used_height,
alignment: 0.0,
}
}
pub(crate) fn resolve(
&self,
style: &Style,
geometry: &crate::layout::geometry::HorizontalBox,
containing_height: Option<f32>,
fragment: Option<SpannerFragment>,
) -> (f32, bool) {
let top_delta = geometry.padding[0] + geometry.border[0] - self.edges[0];
let bottom_delta = geometry.padding[2] + geometry.border[2] - self.edges[1];
let vertical =
crate::layout::geometry::VerticalBox::new(style, geometry, containing_height)
.with_used_height(
self.used_height
.map(|height| (height - self.alignment).max(0.0)),
);
if let Some(mut fragment) = fragment {
fragment.natural_height = (fragment.natural_height + top_delta + bottom_delta).max(0.0);
let natural = self.natural_height
+ if fragment.first || style.clone_decoration {
top_delta
} else {
0.0
}
+ if fragment.last || style.clone_decoration {
bottom_delta
} else {
0.0
};
fragment.resolve_size(style, geometry, &vertical, natural.max(0.0))
} else {
let natural = (self.natural_height + top_delta + bottom_delta).max(0.0);
let height = vertical.used_height(natural);
(height, height != natural || vertical.definite().is_some())
}
}
}
#[derive(Clone)]
pub(super) struct MeasuredBlock<'a> {
pub grid: Option<std::rc::Rc<crate::layout::grid::Geometry<'a>>>,
pub source: &'a BlockBox,
pub geometry: crate::layout::geometry::HorizontalBox,
pub containing_height: Option<f32>,
pub style: &'a Style,
pub canvas_source: bool,
pub offset: [f32; 2],
pub before: MarginStrut<'a>,
pub after: MarginStrut<'a>,
pub clearance_before: Option<Box<MarginStrut<'a>>>,
pub clearance_target: Option<usize>,
pub through: bool,
pub height: f32,
pub sizing: Option<BlockSizing>,
pub constrained: bool,
pub independent: bool,
pub overflow_height: f32,
pub first_fragment: f32,
pub has_forced: bool,
pub break_before: BreakBetween,
pub break_after: BreakBetween,
pub items: Vec<FlowItem<'a>>,
pub paint: Option<BoxPaint>,
pub navigation: BoxNavigation,
pub end_space: f32,
pub start_space: f32,
pub repeat_space: f32,
pub marker: Option<Box<crate::layout::markers::MeasuredMarker>>,
pub table: Option<Box<TableFlow<'a>>>,
pub continues: bool,
pub spanner_fragment: Option<SpannerFragment>,
}
impl MeasuredBlock<'_> {
pub(crate) fn align_cell(&mut self, offset: f32) {
if let Some(sizing) = &mut self.sizing {
sizing.alignment = offset;
(self.height, self.constrained) = sizing.resolve(
self.style,
&self.geometry,
self.containing_height,
self.spanner_fragment,
);
}
}
pub(crate) fn resize_fragment(
&mut self,
geometry: crate::layout::geometry::HorizontalBox,
containing_height: Option<f32>,
fragment: SpannerFragment,
) {
let top = geometry.padding[0] + geometry.border[0];
let bottom = geometry.padding[2] + geometry.border[2];
if (fragment.first || self.style.clone_decoration)
&& let Some(FlowItem::Edge(BlockEdge::Start, space)) = self.items.first_mut()
{
*space = top;
}
if (fragment.last || self.style.clone_decoration)
&& let Some(FlowItem::Edge(BlockEdge::End, space)) = self.items.last_mut()
{
*space = bottom;
}
(self.height, self.constrained) = self
.sizing
.expect("spanner pieces retain their source sizing")
.resolve(self.style, &geometry, containing_height, Some(fragment));
self.spanner_fragment = Some(fragment);
self.overflow_height = overflow_height(&self.items).max(self.height);
self.first_fragment =
crate::layout::breaks::first_fragment(&self.items).min(self.overflow_height);
self.start_space = top;
self.end_space = if fragment.last || self.style.clone_decoration {
bottom
} else {
0.0
};
self.offset = self.style.relative_offset(
geometry.containing_width,
containing_height,
geometry.containing_rtl,
);
if let Some(paint) = &mut self.paint {
paint.rect = geometry.border_box(paint.rect.height);
paint.padding = geometry.padding;
}
self.geometry = geometry;
self.containing_height = containing_height;
}
pub(crate) fn retain_fragment(&mut self) {
self.paint.get_or_insert_with(|| BoxPaint {
padding: self.geometry.padding,
..BoxPaint::whole(
self.geometry.border_box(self.height),
BoxDecoration::default(),
)
});
}
pub(crate) fn first_baseline(&self) -> Option<f32> {
first_baseline(&self.items)
}
pub(crate) fn last_baseline(&self) -> Option<f32> {
last_baseline(&self.items)
}
}
pub(super) fn first_baseline(items: &[FlowItem<'_>]) -> Option<f32> {
let mut y = 0.0;
for item in items {
let baseline = match item {
FlowItem::Paragraph(paragraph) => paragraph.lines.first().map(|line| line.ascent),
FlowItem::Block(block) | FlowItem::Spanner(block) => block.first_baseline(),
FlowItem::Columns(columns) => columns.baselines[0],
FlowItem::Row(row) => row.baselines.map_or_else(
|| {
row.cells.first().and_then(|cell| {
cell.block.first_baseline().map(|value| value + cell.offset)
})
},
|baselines| baselines[0],
),
_ => None,
};
if let Some(baseline) = baseline {
return Some(y + baseline);
}
y += item.height();
}
None
}
pub(super) fn last_baseline(items: &[FlowItem<'_>]) -> Option<f32> {
let mut y = items.iter().map(FlowItem::height).sum::<f32>();
for item in items.iter().rev() {
y -= item.height();
let baseline = match item {
FlowItem::Paragraph(paragraph) => paragraph
.lines
.last()
.map(|line| paragraph.height - line.height + line.ascent),
FlowItem::Block(block) | FlowItem::Spanner(block) => block.last_baseline(),
FlowItem::Columns(columns) => columns.baselines[1],
FlowItem::Row(row) => row.baselines.map_or_else(
|| {
row.cells.first().and_then(|cell| {
cell.block.first_baseline().map(|value| value + cell.offset)
})
},
|baselines| baselines[1],
),
_ => None,
};
if let Some(baseline) = baseline {
return Some(y + baseline);
}
}
None
}
#[derive(Clone)]
pub(super) struct MeasuredParagraph<'a> {
pub index: usize,
pub paragraph: &'a crate::document::Paragraph,
pub style: &'a Style,
pub x: f32,
pub width: f32,
pub containing_height: Option<f32>,
pub height: f32,
pub lines: Vec<Line>,
pub positions: Vec<crate::text::TextPosition<'a>>,
pub anchors: Vec<LineAnchor<'a>>,
pub atomics: Vec<Option<crate::layout::inline::MeasuredAtomic<'a>>>,
pub clamp: Option<crate::text::ParagraphClamp>,
}
#[derive(Clone, Copy)]
pub(super) struct LineBudget {
pub lines: usize,
pub following: bool,
}
fn discards(style: &Style) -> bool {
style.clamp.continuation == crate::style::Continue::Discard
&& matches!(
style.display,
Display::Block
| Display::ListItem
| Display::FlowRoot
| Display::FlowRootListItem
| Display::InlineBlock
| Display::TableCell
| Display::TableCaption
)
}
fn lines_within(items: &[FlowItem<'_>], top: f32, limit: f32, counts: &mut [usize; 2]) {
let mut y = top;
for item in items {
match item {
FlowItem::Paragraph(paragraph) => {
for line in ¶graph.lines {
y += line.height;
if counts[0] == counts[1] && y <= limit {
counts[0] += 1;
}
counts[1] += 1;
}
continue;
}
FlowItem::Block(block) if !block.independent => {
lines_within(&block.items, y, limit, counts);
}
_ => {}
}
y += item.height();
}
}
#[derive(Clone)]
pub(super) struct LineAnchor<'a> {
pub block: &'a BlockBox,
pub line: usize,
pub x: Option<f32>,
pub below: bool,
pub inline_box: Option<usize>,
}
#[derive(Clone)]
pub(super) struct PositionedFlow<'a> {
pub block: &'a BlockBox,
pub left: f32,
pub right: f32,
pub margin: f32,
pub alignment: Option<crate::layout::positioned::StaticAlignment>,
}
#[derive(Clone)]
pub(super) struct MeasuredCell<'a> {
pub clipped_height: Option<f32>,
pub after_events: Vec<&'a crate::document::SemanticEvent>,
pub grid_cell: Option<usize>,
pub backgrounds: Vec<crate::layout::tables::FragmentBackground<'a>>,
pub block: MeasuredBlock<'a>,
pub offset: f32,
pub paint_offset: Option<f32>,
pub stretch: bool,
pub after: f32,
pub flex_item: bool,
}
#[derive(Clone)]
pub(super) struct RowTarget {
pub visible: bool,
pub row: usize,
pub rect: Rect,
pub offset: [f32; 2],
pub navigation: BoxNavigation,
}
#[derive(Clone)]
pub(super) struct CollapsedItem<'a> {
pub source: &'a BlockBox,
pub offset: f32,
pub after_events: Vec<&'a crate::document::SemanticEvent>,
}
#[derive(Clone)]
pub(super) struct MeasuredRow<'a> {
pub grid: Option<std::rc::Rc<crate::layout::grid::Rows>>,
pub baselines: Option<[Option<f32>; 2]>,
pub collapsed: Vec<CollapsedItem<'a>>,
pub background_rows: Vec<crate::layout::tables::BackgroundRows>,
pub cell_heights: Vec<(usize, f32)>,
pub height: f32,
pub first_fragment: f32,
pub paints: Vec<BoxPaint>,
pub targets: Vec<RowTarget>,
pub cells: Vec<MeasuredCell<'a>>,
pub break_before: BreakBetween,
pub break_after: BreakBetween,
pub band: Option<std::ops::Range<usize>>,
}
#[derive(Clone)]
pub(super) struct TableFlow<'a> {
pub row_starts: std::rc::Rc<[f32]>,
pub original_row_starts: Option<std::rc::Rc<[f32]>>,
pub plan: std::rc::Rc<crate::layout::tables::TablePlan<'a>>,
pub geometry: crate::layout::geometry::HorizontalBox,
pub heights: Vec<crate::table::CellHeight>,
pub header: Vec<MeasuredRow<'a>>,
pub footer: Vec<MeasuredRow<'a>>,
pub body: std::ops::Range<usize>,
pub footer_height: f32,
pub spacing: f32,
pub collapsed: Option<crate::layout::tables::CollapsedGrid>,
}
#[derive(Clone, Copy)]
pub(super) enum BlockEdge {
Start,
End,
}
#[derive(Clone)]
pub(super) struct MeasuredTableBox<'a> {
pub area: crate::layout::tables::TableContaining<'a>,
pub edges: [BreakBetween; 2],
pub events: Vec<&'a crate::document::SemanticEvent>,
}
#[derive(Clone)]
pub(super) enum FlowItem<'a> {
Events(&'a [crate::document::SemanticEvent]),
TableBox(Box<MeasuredTableBox<'a>>),
Image {
paint: crate::graphics::ImagePaint,
visible: bool,
height: f32,
},
Block(Box<MeasuredBlock<'a>>),
Paragraph(MeasuredParagraph<'a>),
Margin(MarginStrut<'a>),
Space(f32),
Edge(BlockEdge, f32),
Row(Box<MeasuredRow<'a>>),
Positioned(PositionedFlow<'a>),
Columns(Box<MeasuredColumns<'a>>),
Spanner(Box<MeasuredBlock<'a>>),
}
impl FlowItem<'_> {
pub(crate) fn height(&self) -> f32 {
match self {
Self::Image { height, .. } => *height,
Self::Block(block) | Self::Spanner(block) => block.height,
Self::Columns(columns) => columns.height,
Self::Paragraph(paragraph) => paragraph.height,
Self::Row(row) => row.height,
Self::Margin(margin) => margin.value(),
Self::Space(value) | Self::Edge(_, value) => *value,
Self::Positioned(_) | Self::Events(_) | Self::TableBox(_) => 0.0,
}
}
}
pub(super) fn overflow_height(items: &[FlowItem<'_>]) -> f32 {
let mut position = 0.0;
let mut extent = 0.0f32;
for item in items {
let height = match item {
FlowItem::Block(block) | FlowItem::Spanner(block) => block.overflow_height,
FlowItem::Row(row) => row.cells.iter().fold(row.height, |height, cell| {
height.max(cell.offset + cell.block.overflow_height)
}),
_ => item.height(),
};
extent = extent.max(position + height);
position += item.height();
}
extent
}
#[derive(Clone, Copy)]
pub(crate) struct BlockSource<'a> {
pub block: &'a BlockBox,
pub selected: &'a Style,
}
impl<'a> From<&'a BlockBox> for BlockSource<'a> {
fn from(block: &'a BlockBox) -> Self {
Self {
block,
selected: block.style(),
}
}
}
impl std::ops::Deref for BlockSource<'_> {
type Target = BlockBox;
fn deref(&self) -> &Self::Target {
self.block
}
}
impl<'a> BlockSource<'a> {
pub(crate) fn style(self) -> &'a Style {
self.selected
}
pub(crate) fn children(self) -> &'a [BlockContent] {
self.block.children()
}
pub(crate) fn marker(self) -> Option<&'a crate::document::Paragraph> {
self.block.marker()
}
}
pub(super) struct Measurer<'a> {
pub work: crate::layout::work::Budget,
pub text: &'a TextContext<'a>,
pub canvas_images: bool,
pub page_height: f32,
pub sources: crate::layout::source::SourceIds,
pub clearance_targets: std::collections::HashMap<*const BlockBox, usize>,
pub grid_parent: Option<crate::layout::grid::ParentContext>,
pub item_metrics: std::collections::HashMap<MetricsKey, ItemMetrics>,
pub fragmentainer: Fragmentainer,
pub column_flow: Option<ColumnFlow>,
pub spanner: Option<*const BlockBox>,
pub unbroken: bool,
pub named_pages: bool,
pub container_sizes: std::collections::HashMap<crate::dom::ElementId, [f32; 2]>,
}
impl Measurer<'_> {
pub(crate) fn intrinsic_widths(
&self,
paragraph: &crate::document::Paragraph,
atomics: &[crate::text::IntrinsicWidths],
) -> Result<crate::text::IntrinsicWidths, LayoutError> {
self.work.spend(paragraph.text().len().max(1))?;
Ok(self.text.intrinsic_widths(paragraph, atomics)?)
}
pub(crate) fn text_lines(
&self,
paragraph: &crate::document::Paragraph,
width: f32,
atomics: &[crate::text::AtomicMetrics],
) -> Result<Vec<Line>, LayoutError> {
self.work.spend(paragraph.text().len().max(1))?;
Ok(self.text.layout_paragraph(paragraph, width, atomics)?)
}
pub(super) fn box_paint<'a>(
&self,
block: impl Into<BlockSource<'a>>,
geometry: &crate::layout::geometry::HorizontalBox,
) -> Option<BoxPaint> {
let block = block.into();
let style = block.style();
let mut decoration = block.decoration().clone();
if block.is_canvas_source() && !self.canvas_images {
decoration.clear_background();
}
let fragments = (block.is_canvas_source() && self.canvas_images)
|| style.clipped_axes().contains(&true)
|| style.decoration.masks.is_masked()
|| style.contains_absolute()
|| style.is_scroll_container()
|| contains_sticky(block.block)
|| bounds_enclosing_inline(block.block)
|| !block.navigation().is_empty();
let rect = geometry.border_box(0.0);
(style.display != Display::None && (decoration.is_visible() || fragments)).then(|| {
BoxPaint {
draw_background: !block.is_canvas_source(),
padding: geometry.padding,
margins: geometry.used_margins(),
..BoxPaint::whole(rect, decoration)
}
})
}
pub(crate) fn block<'a>(
&mut self,
block: &'a BlockBox,
x: f32,
width: f32,
containing_rtl: bool,
root: bool,
containing_height: Option<f32>,
) -> Result<MeasuredBlock<'a>, LayoutError> {
let style = block.style();
if style.display.is_table() {
return crate::layout::tables::measure(
self,
block,
x,
width,
containing_rtl,
containing_height,
);
}
let geometry = block_geometry(self, block, x, width, containing_rtl, containing_height)?;
self.format_block(block, geometry, root, containing_height, None)
}
fn spanner<'a>(
&mut self,
child: &'a BlockBox,
flow: ColumnFlow,
) -> Result<MeasuredBlock<'a>, LayoutError> {
let saved = (self.fragmentainer, self.spanner);
self.fragmentainer = flow.fragmentainer;
self.spanner = Some(child);
let measured = self.block(
child,
flow.x,
flow.width,
flow.rtl,
false,
flow.containing_height,
);
(self.fragmentainer, self.spanner) = saved;
measured
}
pub(super) fn format_block<'a>(
&mut self,
block: impl Into<BlockSource<'a>>,
geometry: crate::layout::geometry::HorizontalBox,
root: bool,
containing_height: Option<f32>,
used_height: Option<f32>,
) -> Result<MeasuredBlock<'a>, LayoutError> {
self.measure_flow(
block.into(),
geometry,
root,
containing_height,
used_height,
None,
)
}
fn measure_flow<'a>(
&mut self,
block: BlockSource<'a>,
geometry: crate::layout::geometry::HorizontalBox,
root: bool,
containing_height: Option<f32>,
used_height: Option<f32>,
budget: Option<LineBudget>,
) -> Result<MeasuredBlock<'a>, LayoutError> {
let context = (self.fragmentainer, self.column_flow);
let measured = if discards(block.style()) {
self.discarding_flow(
block,
geometry,
root,
containing_height,
used_height,
budget,
)
} else {
self.format_flow(block, geometry, root, containing_height, used_height, None)
};
(self.fragmentainer, self.column_flow) = context;
measured
}
fn discarding_flow<'a>(
&mut self,
block: BlockSource<'a>,
geometry: crate::layout::geometry::HorizontalBox,
root: bool,
containing_height: Option<f32>,
used_height: Option<f32>,
outer: Option<LineBudget>,
) -> Result<MeasuredBlock<'a>, LayoutError> {
let style = block.style();
if style.multicol.is_multicol() {
return Err(LayoutError::UnsupportedClamp {
feature: "continue: discard on a multi-column container",
});
}
let budget = match (style.clamp.max_lines, outer) {
(Some(lines), Some(outer)) => Some(LineBudget {
lines: lines.min(outer.lines),
following: outer.following && outer.lines <= lines,
}),
(Some(lines), None) => Some(LineBudget {
lines,
following: false,
}),
(None, outer) => outer,
};
let context = (self.fragmentainer, self.column_flow);
let measured = self.format_flow(
block,
geometry.clone(),
root,
containing_height,
used_height,
budget,
)?;
if measured
.sizing
.is_none_or(|sizing| sizing.natural_height <= measured.height)
{
return Ok(measured);
}
let mut counts = [0; 2];
lines_within(
&measured.items,
0.0,
measured.height - measured.end_space,
&mut counts,
);
let [fitting, total] = counts;
if fitting >= total {
return Ok(measured);
}
(self.fragmentainer, self.column_flow) = context;
self.format_flow(
block,
geometry,
root,
containing_height,
used_height,
Some(LineBudget {
lines: fitting.max(1),
following: true,
}),
)
}
fn budget(frames: &[FlowFrame<'_>]) -> Option<usize> {
let clamp = frames[0].clamp.as_ref()?;
(!frames[1..].iter().any(|frame| frame.independent)).then_some(clamp.remaining)
}
fn following(frames: &[FlowFrame<'_>]) -> bool {
frames[0]
.clamp
.as_ref()
.is_some_and(|clamp| clamp.following)
|| frames.iter().any(|frame| {
frame
.children
.clone()
.any(|child| matches!(child, BlockContent::Block(_) | BlockContent::Inline(_)))
})
}
fn spend_lines(frames: &mut [FlowFrame<'_>], lines: usize, broken: bool) {
let Some(clamp) = frames[0].clamp.as_mut() else {
return;
};
clamp.remaining = clamp.remaining.saturating_sub(lines);
if broken {
for frame in frames.iter_mut() {
frame.children = [].iter();
}
for frame in &mut frames[1..] {
frame.fragmented = true;
}
}
}
fn start_flow<'a>(
&mut self,
block: BlockSource<'a>,
geometry: crate::layout::geometry::HorizontalBox,
root: bool,
containing_height: Option<f32>,
used_height: Option<f32>,
) -> Result<FlowStart<'a>, LayoutError> {
self.work.spend(1)?;
let restore_column_flow = self.column_flow;
let style = block.style();
let spanning = self
.spanner
.is_some_and(|spanner| std::ptr::eq(spanner, block.block));
if spanning
|| !matches!(style.display, Display::Block | Display::ListItem)
|| style.establishes_formatting_context()
{
self.column_flow = None;
}
let started = (|| {
let index = self.sources.block(block.block);
if !geometry.width.is_finite()
|| !geometry.x.is_finite()
|| geometry
.padding
.iter()
.chain(geometry.margin.iter().flatten())
.any(|p| !p.is_finite())
{
return Err(LayoutError::NonFiniteBlockGeometry { block: index });
}
if block.image().is_some() {
return crate::layout::images::measure(
self,
block,
&geometry,
containing_height,
used_height,
)
.map(FlowStart::Complete);
}
if style.display.is_grid() {
return crate::layout::grid::measure(
self,
block,
&geometry,
containing_height,
used_height,
)
.map(FlowStart::Complete);
}
if style.display.is_flex() {
return crate::layout::flex::measure(
self,
block,
&geometry,
containing_height,
used_height,
)
.map(FlowStart::Complete);
}
let vertical =
crate::layout::geometry::VerticalBox::new(style, &geometry, containing_height)
.with_used_height(used_height);
let marker = if let Some(paragraph) = block.marker() {
let index = self.sources.paragraph(paragraph);
Some(Box::new(crate::layout::markers::measure(
paragraph,
self,
index,
geometry.x - geometry.padding[3] - geometry.border[3],
geometry.x + geometry.width + geometry.padding[1] + geometry.border[1],
super::anchors::key(style),
)?))
} else {
None
};
let top_edge = geometry.padding[0] + geometry.border[0];
let bottom_edge = geometry.padding[2] + geometry.border[2];
let independent = style.establishes_formatting_context() || spanning;
let edges = self.fragmentainer.edges(style);
let columns = (style.display != Display::None && style.multicol.is_multicol())
.then(|| ColumnGeometry::resolve(style, geometry.x, geometry.width));
let (content_x, content_width) = columns
.as_ref()
.map_or((geometry.x, geometry.width), |columns| {
(columns.left(0), columns.width)
});
let outer = (self.fragmentainer, self.column_flow);
if columns.is_some() {
self.fragmentainer = Fragmentainer::Column;
self.column_flow = Some(ColumnFlow {
x: geometry.x,
width: geometry.width,
rtl: style.rtl,
containing_height: vertical.definite(),
fragmentainer: outer.0,
});
}
let visible = style.display != Display::None;
Ok(FlowStart::Pending(FlowFrame {
block,
root,
index,
containing_height,
used_height,
cell_percentage_chain: false,
vertical,
before: MarginStrut::edge(block.block, 0, geometry.containing_width),
after: MarginStrut::edge(block.block, 2, geometry.containing_width),
geometry,
pending: MarginStrut::default(),
items: if visible {
vec![FlowItem::Edge(BlockEdge::Start, top_edge)]
} else {
Vec::new()
},
at_start: true,
top_edge,
bottom_edge,
independent,
collapse_top: !root && !independent && top_edge == 0.0,
edges,
has_forced: edges.iter().any(|edge| edge.is_forced()),
columns,
content_x,
content_width,
outer,
restore_column_flow,
previous_break_after: BreakBetween::Auto,
children: if visible { block.children() } else { &[] }.iter(),
marker,
clamp: None,
fragmented: false,
}))
})();
if !matches!(&started, Ok(FlowStart::Pending(_))) {
self.column_flow = restore_column_flow;
}
started
}
fn format_flow<'a>(
&mut self,
block: BlockSource<'a>,
geometry: crate::layout::geometry::HorizontalBox,
root: bool,
containing_height: Option<f32>,
used_height: Option<f32>,
budget: Option<LineBudget>,
) -> Result<MeasuredBlock<'a>, LayoutError> {
let mut frames =
match self.start_flow(block, geometry, root, containing_height, used_height)? {
FlowStart::Complete(measured) => return Ok(measured),
FlowStart::Pending(mut frame) => {
frame.clamp = budget.map(|budget| FrameClamp {
remaining: budget.lines,
following: budget.following,
});
vec![frame]
}
};
loop {
let frame = frames.last_mut().unwrap();
let child = frame.children.next();
match child {
Some(BlockContent::Events(events)) => frame.items.push(FlowItem::Events(events)),
Some(BlockContent::Positioned(child)) => {
frame.items.push(FlowItem::Positioned(PositionedFlow {
block: child,
left: frame.content_x,
right: frame.content_x + frame.content_width,
margin: frame.pending.value(),
alignment: None,
}));
}
Some(BlockContent::Block(child)) => {
if let Some(flow) = self.column_flow.filter(|_| child.style().multicol.span_all)
{
frame.push_block(self.spanner(child, flow)?, true);
} else if child.style().display.is_table() {
frame.push_block(
self.block(
child,
frame.content_x,
frame.content_width,
frame.block.style().rtl,
false,
frame.vertical.definite(),
)?,
false,
);
} else if discards(child.style()) {
let geometry = block_geometry(
self,
child,
frame.content_x,
frame.content_width,
frame.block.style().rtl,
frame.vertical.definite(),
)?;
let containing = frame.vertical.definite();
let budget = Self::budget(&frames).map(|lines| LineBudget {
lines,
following: Self::following(&frames),
});
let measured = self.measure_flow(
child.into(),
geometry,
false,
containing,
None,
budget,
)?;
let mut counts = [0; 2];
if !measured.independent {
lines_within(&measured.items, 0.0, f32::INFINITY, &mut counts);
}
let broken = budget
.is_some_and(|budget| counts[1] >= budget.lines && budget.following);
frames.last_mut().unwrap().push_block(measured, false);
if budget.is_some() {
Self::spend_lines(&mut frames, counts[1], broken);
}
} else {
let geometry = block_geometry(
self,
child,
frame.content_x,
frame.content_width,
frame.block.style().rtl,
frame.vertical.definite(),
)?;
let child_style = child.style();
let cell_percentage_chain = (frame.block.style().display
== Display::TableCell
|| frame.cell_percentage_chain)
&& frame.vertical.definite().is_none()
&& child.image().is_none()
&& matches!(child_style.height, crate::style::Size::Value(_))
&& child_style.height.resolve_definite(None).is_none();
let used_height = (cell_percentage_chain
&& matches!(
child_style.overflow[1],
crate::style::Overflow::Auto | crate::style::Overflow::Scroll
))
.then(|| {
let edges = geometry.padding[0]
+ geometry.padding[2]
+ geometry.border[0]
+ geometry.border[2];
crate::style::SizeConstraints::new(
[
&crate::style::Size::ZERO,
&child_style.min_height,
&child_style.max_height,
],
None,
child_style.box_sizing,
edges,
)
.constrain(0.0)
});
match self.start_flow(
child.into(),
geometry,
false,
frame.vertical.definite(),
used_height,
)? {
FlowStart::Complete(measured) => frame.push_block(measured, false),
FlowStart::Pending(mut frame) => {
frame.cell_percentage_chain = cell_percentage_chain;
frames.push(frame);
}
}
}
}
Some(BlockContent::Inline(paragraph)) => {
let (x, width, containing, rtl) = (
frame.content_x,
frame.content_width,
frame.vertical.definite(),
frame.block.style().rtl,
);
let budget = Self::budget(&frames).map(|lines| LineBudget {
lines,
following: Self::following(&frames),
});
let paragraph = self.paragraph(paragraph, x, width, containing, rtl, budget)?;
let (lines, broken) = (paragraph.lines.len(), paragraph.clamp.is_some());
let frame = frames.last_mut().unwrap();
frame.previous_break_after = BreakBetween::Auto;
frame.push(FlowItem::Paragraph(paragraph));
if budget.is_some() {
Self::spend_lines(&mut frames, lines, broken);
}
}
None => {
let frame = frames.pop().unwrap();
let restore = frame.restore_column_flow;
let measured = frame.finish(self)?;
self.column_flow = restore;
if let Some(parent) = frames.last_mut() {
parent.push_block(measured, false);
} else {
return Ok(measured);
}
}
}
}
}
fn paragraph<'a>(
&mut self,
paragraph: &'a crate::document::Paragraph,
x: f32,
width: f32,
containing_height: Option<f32>,
rtl: bool,
budget: Option<LineBudget>,
) -> Result<MeasuredParagraph<'a>, LayoutError> {
self.work.spend(paragraph.text().len().max(1))?;
let index = self.sources.paragraph(paragraph);
let atomics = paragraph
.inline_blocks()
.map(|atomic| {
crate::layout::inline::measure(self, &atomic.block, width, containing_height, rtl)
})
.collect::<Result<Vec<_>, _>>()?;
let metrics: Vec<_> = atomics.iter().map(|atomic| atomic.metrics).collect();
let text = self.text;
let prepared = text.prepare_paragraph(paragraph);
let mut stream = prepared.lines(prepared.start(), width, &metrics)?;
let mut lines = Vec::new();
let mut positions = vec![stream.checkpoint()];
let limit = budget.map_or(usize::MAX, |budget| budget.lines);
while lines.len() < limit
&& let Some(line) = stream.next()
{
self.work.spend(1)?;
lines.push(line?);
positions.push(stream.checkpoint());
}
let more = lines.len() == limit && stream.next().transpose()?.is_some();
let clamp = budget
.filter(|budget| lines.len() == budget.lines && (more || budget.following))
.map(|budget| crate::text::ParagraphClamp {
lines: budget.lines,
ellipsis: Some(paragraph.style().clamp.block_ellipsis.clone())
.filter(|ellipsis| *ellipsis != crate::style::BlockEllipsis::None),
});
if let Some(clamp) = clamp.as_ref().filter(|clamp| clamp.ellipsis.is_some()) {
let clamped = text
.prepare_paragraph(paragraph)
.clamped(Some(clamp.clone()));
let mut stream = clamped.lines(positions[clamp.lines - 1], width, &metrics)?;
if let Some(line) = stream.next() {
lines[clamp.lines - 1] = line?;
positions[clamp.lines] = stream.checkpoint();
}
}
let rise = atomics
.first()
.and_then(|atomic| atomic.letter)
.map_or(0.0, |letter| letter.rise());
let height = lines.iter().map(|line| line.height).sum::<f32>() + rise;
let anchors = line_anchors(paragraph, &lines, clamp.is_none());
Ok(MeasuredParagraph {
index,
paragraph,
style: paragraph.style(),
x,
width,
containing_height,
height,
lines,
positions,
anchors,
atomics: atomics.into_iter().map(Some).collect(),
clamp,
})
}
}
pub(super) fn block_geometry(
measurer: &Measurer<'_>,
block: &BlockBox,
x: f32,
width: f32,
rtl: bool,
containing_height: Option<f32>,
) -> Result<crate::layout::geometry::HorizontalBox, LayoutError> {
let style = block.style();
let edges = crate::layout::geometry::Edges::of(style, width);
let used_width = match block.image() {
Some(_) => {
Some(crate::layout::images::size(block, width, width, containing_height, None, None)[0])
}
None => crate::layout::ratio::width_from_height(
measurer,
block,
width,
containing_height,
&edges,
)?,
};
let geometry = horizontal(style, x, width, rtl, used_width);
let transfers = crate::layout::ratio::PreferredRatio::of_box(style, &edges).is_some();
if used_width.is_some()
|| (!transfers
&& ![&style.width, &style.min_width, &style.max_width]
.iter()
.any(|size| matches!(size, crate::style::Size::Intrinsic(_))))
{
return Ok(geometry);
}
let margins = [geometry.margin[3], geometry.margin[1]];
let available =
(width - edges.horizontal() - margins[0].unwrap_or(0.0) - margins[1].unwrap_or(0.0))
.max(0.0);
let mut constraints = crate::layout::intrinsic::width_constraints(
block,
measurer,
Some(width),
edges.horizontal(),
Some(available),
)?;
crate::layout::ratio::transfer_to_width(style, &mut constraints, containing_height, &edges);
let used = constraints.normal_flow(
width,
edges.horizontal(),
margins,
None,
rtl,
crate::style::Overconstraint::AdjustEndMargin,
);
Ok(horizontal(style, x, width, rtl, Some(used.size)))
}
enum FlowStart<'a> {
Complete(MeasuredBlock<'a>),
Pending(FlowFrame<'a>),
}
struct FlowFrame<'a> {
block: BlockSource<'a>,
geometry: crate::layout::geometry::HorizontalBox,
root: bool,
index: usize,
containing_height: Option<f32>,
used_height: Option<f32>,
cell_percentage_chain: bool,
vertical: crate::layout::geometry::VerticalBox,
before: MarginStrut<'a>,
after: MarginStrut<'a>,
pending: MarginStrut<'a>,
items: Vec<FlowItem<'a>>,
at_start: bool,
top_edge: f32,
bottom_edge: f32,
independent: bool,
collapse_top: bool,
edges: [BreakBetween; 2],
has_forced: bool,
columns: Option<ColumnGeometry>,
content_x: f32,
content_width: f32,
outer: (Fragmentainer, Option<ColumnFlow>),
restore_column_flow: Option<ColumnFlow>,
previous_break_after: BreakBetween,
children: std::slice::Iter<'a, BlockContent>,
marker: Option<Box<crate::layout::markers::MeasuredMarker>>,
clamp: Option<FrameClamp>,
fragmented: bool,
}
struct FrameClamp {
remaining: usize,
following: bool,
}
impl<'a> FlowFrame<'a> {
fn push(&mut self, item: FlowItem<'a>) {
let cleared = matches!(&item, FlowItem::Block(block) | FlowItem::Spanner(block) if block.clearance_target.is_some());
if self.at_start && self.collapse_top && !cleared {
self.before
.merge(self.pending.clone().within(self.block.block));
} else {
let mut margin = self.pending.clone();
if let FlowItem::Block(block) | FlowItem::Spanner(block) = &item
&& block.clearance_before.is_some()
{
margin = margin.for_clearance(block.source);
}
self.items.push(FlowItem::Margin(margin));
}
self.pending = match &item {
FlowItem::Block(block) | FlowItem::Spanner(block) => block.after.clone(),
_ => MarginStrut::default(),
};
self.items.push(item);
self.at_start = false;
}
fn push_block(&mut self, mut block: MeasuredBlock<'a>, spanner: bool) {
if block.style.clear != crate::style::Clear::None || block.clearance_before.is_some() {
block.clearance_before = Some(Box::new(self.pending.clone()));
}
self.has_forced |= block.has_forced;
self.pending.merge(
if self.previous_break_after.is_forced() || block.break_before.is_forced() {
block.before.clone().after_forced_break()
} else {
block.before.clone()
},
);
self.previous_break_after = block.break_after;
if spanner {
self.push(FlowItem::Spanner(Box::new(block)));
} else if block.through {
self.pending.merge(block.after.clone());
self.items.push(FlowItem::Block(Box::new(block)));
} else {
self.push(FlowItem::Block(Box::new(block)));
}
}
fn finish(self, measurer: &mut Measurer<'_>) -> Result<MeasuredBlock<'a>, LayoutError> {
let Self {
block,
geometry,
root,
index,
containing_height,
used_height,
vertical,
mut before,
mut after,
mut pending,
mut items,
at_start,
top_edge,
mut bottom_edge,
independent,
edges,
mut has_forced,
columns,
outer,
marker,
fragmented,
..
} = self;
let style = block.style();
if fragmented {
pending = MarginStrut::default();
after = MarginStrut::default();
if !style.clone_decoration {
bottom_edge = 0.0;
}
}
let clearance_target = measurer
.clearance_targets
.get(&std::ptr::from_ref::<BlockBox>(block.block))
.copied();
let through = clearance_target.is_none()
&& !root
&& !independent
&& at_start
&& top_edge == 0.0
&& bottom_edge == 0.0
&& vertical.collapse_through();
if through {
before.merge(pending.clone().within(block.block));
before.merge(after);
after = MarginStrut::default();
} else if !root && !independent && bottom_edge == 0.0 && vertical.collapse_bottom() {
let mut collapsed = pending.within(block.block);
collapsed.merge(after);
after = collapsed;
} else {
items.push(FlowItem::Margin(pending));
}
(measurer.fragmentainer, measurer.column_flow) = outer;
if let Some(columns) = columns {
let content = items.split_off(1);
let columns = crate::layout::multicol::measure(
measurer,
columns,
style,
content,
vertical.definite(),
)?;
has_forced = edges.iter().any(|edge| edge.is_forced()) || columns.forces_page;
items.push(FlowItem::Columns(Box::new(columns)));
}
items.push(FlowItem::Edge(BlockEdge::End, bottom_edge));
let legend = place_legend(&mut items, &geometry);
let top_edge = legend.map_or(top_edge, |(_, start)| start);
let mut height = items.iter().map(FlowItem::height).sum::<f32>();
if !height.is_finite() {
return Err(LayoutError::NonFiniteBlockGeometry { block: index });
}
if height < 0.0 {
items.push(FlowItem::Space(-height));
height = 0.0;
}
let mut natural_height = height;
height = vertical.used_height(height);
if !height.is_finite() {
return Err(LayoutError::NonFiniteBlockGeometry { block: index });
}
let constrained = height != natural_height || vertical.definite().is_some();
let alignment = content_alignment(style, height - natural_height);
if alignment != 0.0 {
items.insert(1, FlowItem::Space(alignment));
natural_height += alignment;
}
let overflow_height = overflow_height(&items).max(height);
let first_fragment = if measurer.fragmentainer.keeps(style)
&& !has_forced
&& overflow_height <= measurer.page_height
{
overflow_height
} else {
(crate::layout::breaks::first_fragment(&items)
+ if style.clone_decoration {
bottom_edge
} else {
0.0
})
.min(overflow_height)
};
let (break_before, break_after) = crate::layout::breaks::boundaries(style, &items, edges);
let mut paint = measurer.box_paint(block, &geometry);
if let Some(paint) = &mut paint {
paint.legend = legend.map(|(cut, _)| cut);
}
Ok(MeasuredBlock {
grid: None,
source: block.block,
geometry: geometry.clone(),
containing_height,
offset: style.relative_offset(
geometry.containing_width,
containing_height,
geometry.containing_rtl,
),
style,
canvas_source: block.is_canvas_source(),
clearance_before: (style.clear != crate::style::Clear::None || items.iter().any(|item| matches!(item, FlowItem::Block(child) | FlowItem::Spanner(child) if child.clearance_before.is_some()))).then(|| Box::new(MarginStrut::default())),
clearance_target,
before,
after,
through,
height,
sizing: Some(BlockSizing::new(natural_height, &geometry, used_height)),
constrained,
independent: root || independent,
overflow_height,
first_fragment,
has_forced,
break_before,
break_after,
items,
paint,
navigation: block.navigation(),
end_space: bottom_edge,
start_space: top_edge,
repeat_space: 0.0,
marker,
table: None,
continues: false,
spanner_fragment: None,
})
}
}
fn place_legend(
items: &mut [FlowItem<'_>],
geometry: &crate::layout::geometry::HorizontalBox,
) -> Option<(crate::graphics::LegendCut, f32)> {
let index = items
.iter()
.position(|item| matches!(item, FlowItem::Block(_)))?;
let (FlowItem::Edge(BlockEdge::Start, _), FlowItem::Margin(_), FlowItem::Margin(_)) = (
items.first()?,
items.get(index.checked_sub(1)?)?,
items.get(index + 1)?,
) else {
return None;
};
let FlowItem::Block(legend) = &items[index] else {
unreachable!("the legend position holds a block")
};
if !legend.source.is_rendered_legend() {
return None;
}
let border = geometry.border[0];
let height = legend.height;
let legend_box = legend.geometry.border_box(height);
let fieldset_box = geometry.border_box(0.0);
let [before, after] = [index - 1, index + 1].map(|at| items[at].height());
let outer = before + height + after;
let area = border.max(outer);
let (top, inset) = if outer > border {
(0.0, before + (height - border) / 2.0)
} else {
((border - height) / 2.0 - before, 0.0)
};
items[0] = FlowItem::Edge(BlockEdge::Start, top);
items[index + 1] = FlowItem::Space(area - top - before - height);
Some((
crate::graphics::LegendCut {
inset,
gap: [
legend_box.x - fieldset_box.x,
legend_box.x - fieldset_box.x + legend_box.width,
],
},
top,
))
}
fn content_alignment(style: &Style, free: f32) -> f32 {
use crate::style::Alignment;
let (factor, safe) = match style.flex.align_content {
Alignment::Center => (0.5, false),
Alignment::End | Alignment::FlexEnd => (1.0, false),
Alignment::SpaceAround | Alignment::SpaceEvenly => (0.5, true),
_ => return 0.0,
};
let safe = !style.flex.align_content_unsafe && (safe || style.is_scroll_container());
if free < 0.0 && safe {
return 0.0;
}
free * factor
}
fn is_sticky(style: &Style) -> bool {
style.position == crate::style::Position::Sticky
}
fn contains_sticky(block: &BlockBox) -> bool {
let sticky = |child: &BlockBox| {
is_sticky(child.style())
|| child
.enclosing_inline()
.iter()
.any(|style| is_sticky(style))
};
block.children().iter().any(|child| match child {
BlockContent::Block(child) | BlockContent::Positioned(child) => sticky(child),
BlockContent::Inline(paragraph) => {
paragraph
.inline_blocks()
.any(|atomic| sticky(&atomic.block))
|| paragraph
.boxes()
.iter()
.any(|inline| is_sticky(&inline.style))
}
BlockContent::Events(_) => false,
})
}
fn bounds_enclosing_inline(block: &BlockBox) -> bool {
block
.enclosing_inline()
.iter()
.any(|style| is_sticky(style) || style.is_filtered() || style.decoration.masks.is_masked())
}
pub(super) fn line_anchors<'a>(
paragraph: &'a crate::document::Paragraph,
lines: &[Line],
complete: bool,
) -> Vec<LineAnchor<'a>> {
let rtl = paragraph.style().rtl;
paragraph
.anchors()
.iter()
.filter(|anchor| anchor.block.style().floating().is_none())
.filter(|anchor| {
complete
|| lines.last().is_some_and(|line| {
if anchor.block.style().inline_level_origin {
anchor.offset < line.range.end
} else {
anchor.offset <= line.range.end
}
})
})
.map(|anchor| {
let block = &anchor.block;
let last = lines.len().saturating_sub(1);
if block.style().inline_level_origin {
let line = lines
.iter()
.position(|line| anchor.offset < line.range.end)
.unwrap_or(last);
LineAnchor {
block,
line,
x: lines.get(line).map(|line| line.x_at(anchor.offset, rtl)),
below: false,
inline_box: anchor.inline_box,
}
} else {
let line = lines
.iter()
.position(|line| anchor.offset <= line.range.end)
.unwrap_or(last);
LineAnchor {
block,
line,
x: None,
below: anchor.offset > 0 && !lines.is_empty(),
inline_box: anchor.inline_box,
}
}
})
.collect()
}