use crate::document::navigation::{BoxNavigation, NavigationBuilder};
use crate::document::{DocumentError, Paragraph, inline::InlineCollector};
use crate::dom::{ChildNodes, DocumentTree, Element, ElementId, TreeRelation};
use crate::graphics::BoxDecoration;
use crate::style::{Display, GeneratedPseudoElement, PseudoElement, Style, StyleError, Stylesheet};
pub(super) const MAX_FORMATTING_DEPTH: usize = 512;
const DEFAULT_DENSITY: f32 = 1.0;
pub(super) const FORMATTING_NESTING_RESOURCE: &str = "formatting nesting";
pub(super) fn background_only<I>(
decoration: &crate::paint::BoxDecoration<I>,
) -> crate::paint::BoxDecoration<I> {
crate::paint::BoxDecoration {
background: decoration.background,
backgrounds: decoration.backgrounds.clone(),
..Default::default()
}
}
const PAPER: crate::graphics::Color = crate::graphics::Color::WHITE;
fn canvas_surface(
mut canvas: BoxDecoration,
surface: Option<crate::graphics::Color>,
) -> BoxDecoration {
let Some(surface) = surface else {
return canvas;
};
let background = canvas.background;
let channel = |index: usize| {
(f32::from(background.rgb[index]) * background.alpha
+ f32::from(surface.rgb[index]) * (1.0 - background.alpha))
.round() as u8
};
canvas.background = crate::graphics::Color {
rgb: [channel(0), channel(1), channel(2)],
alpha: surface.alpha,
};
canvas
}
fn surface_beneath(sheet: &Stylesheet, root: &Style) -> Option<crate::graphics::Color> {
let surface = sheet.canvas_surface(root);
match sheet.presentation() {
crate::style::Presentation::Paged => (surface != PAPER).then_some(surface),
crate::style::Presentation::Viewport { color_scheme } => {
(sheet.used_color_scheme(&root.color_scheme) != color_scheme).then_some(surface)
}
}
}
pub(crate) struct PageBox {
pub request: crate::style::PageRequest,
pub geometry: crate::style::PageGeometry,
#[cfg(test)]
pub style: Style,
pub production: crate::style::PageProduction,
pub decoration: BoxDecoration,
pub margins: Vec<PageMarginBox>,
}
pub(crate) struct PageMarginBox {
pub margin: crate::style::PageMargin,
pub decoration: BoxDecoration,
}
pub(crate) struct Formatted {
pub root: BlockBox,
pub navigation: NavigationBuilder,
pub strings: crate::document::strings::StringAssignments,
pub generated: crate::document::generated::GeneratedReferences,
pub canvas: BoxDecoration,
pub pages: crate::document::page::PageProvider,
pub svg_definitions: crate::document::svg::SvgDefinitions,
}
pub(crate) struct BlockBox {
style: Box<Style>,
decoration: BoxDecoration,
shape_outside: crate::graphics::ShapeOutside,
children: Vec<BlockContent>,
marker: Option<Box<Paragraph>>,
image: Option<std::sync::Arc<crate::images::Image>>,
empty_image_fallback: bool,
density: f32,
navigation: BoxNavigation,
canvas_source: bool,
event: Option<crate::document::SemanticEvent>,
page: crate::document::PageBoundary,
anonymous: bool,
query_container: Option<ElementId>,
enclosing_inline: Vec<std::sync::Arc<Style>>,
initial_letter: Option<InitialLetterBox>,
rendered_legend: bool,
}
#[derive(Clone, Copy)]
pub(crate) struct InitialLetterBox {
pub surrounding: crate::text::LetterSurrounding,
pub atomic: bool,
}
pub(crate) enum BlockContent {
Events(Vec<crate::document::SemanticEvent>),
Block(BlockBox),
Inline(Paragraph),
Positioned(BlockBox),
}
impl BlockBox {
pub(super) fn anonymous(
style: Style,
children: Vec<BlockContent>,
page_scope: Option<std::sync::Arc<str>>,
) -> Self {
let decoration = style.decoration.with_image_type();
Self {
anonymous: true,
..Self::with_decoration(style, children, decoration, page_scope)
}
}
pub(super) fn anonymous_replaced(
style: Style,
image: std::sync::Arc<crate::images::Image>,
page_scope: Option<std::sync::Arc<str>>,
) -> Self {
Self {
image: Some(image),
..Self::anonymous(style, Vec::new(), page_scope)
}
}
pub(crate) fn is_anonymous(&self) -> bool {
self.anonymous
}
pub(super) fn with_decoration(
style: Style,
children: Vec<BlockContent>,
decoration: BoxDecoration,
page_scope: Option<std::sync::Arc<str>>,
) -> Self {
let children = if style.display.is_item_container() {
let mut items = Vec::with_capacity(children.len());
for child in children {
match child {
BlockContent::Inline(paragraph) => {
if paragraph
.text()
.chars()
.all(crate::document::inline::is_css_whitespace)
{
items.extend(paragraph.into_non_text());
} else {
items.push(BlockContent::Block(Self::anonymous(
style.anonymous(Display::Block),
vec![BlockContent::Inline(paragraph)],
page_scope.clone(),
)));
}
}
child => items.push(child),
}
}
items
} else {
children
};
let mut children =
crate::document::tables::normalize(&style, children, page_scope.as_ref());
if style.flex.legacy_box {
for child in &mut children {
if let BlockContent::Block(block) = child {
block.style.clamp = crate::style::LineClamp {
continuation: match style.clamp.continuation {
crate::style::Continue::WebkitDiscard
if style.flex.direction.column() =>
{
crate::style::Continue::Discard
}
crate::style::Continue::WebkitDiscard => crate::style::Continue::Auto,
continuation => continuation,
},
..style.clamp.clone()
};
}
}
}
let page = crate::document::PageBoundary::new(page_scope, &style, &children);
Self {
style: Box::new(style),
decoration,
shape_outside: crate::graphics::ShapeOutside::None,
children,
marker: None,
image: None,
empty_image_fallback: false,
density: DEFAULT_DENSITY,
navigation: BoxNavigation::default(),
canvas_source: false,
event: None,
page,
anonymous: false,
query_container: None,
enclosing_inline: Vec::new(),
initial_letter: None,
rendered_legend: false,
}
}
pub(crate) fn leading_events(&self) -> impl Iterator<Item = &crate::document::SemanticEvent> {
self.children
.iter()
.take_while(|child| matches!(child, BlockContent::Events(_)))
.flat_map(|child| match child {
BlockContent::Events(events) => events.as_slice(),
_ => &[],
})
}
pub(crate) fn following_events<'a>(
&'a self,
preceding: &BlockBox,
) -> impl Iterator<Item = &'a crate::document::SemanticEvent> {
let boundary = self
.children
.iter()
.position(|child| match child {
BlockContent::Block(block) | BlockContent::Positioned(block) => {
std::ptr::eq(block, preceding)
}
_ => false,
})
.map_or(self.children.len(), |index| index + 1);
self.children[boundary..]
.iter()
.take_while(|child| matches!(child, BlockContent::Events(_)))
.flat_map(|child| match child {
BlockContent::Events(events) => events.as_slice(),
_ => &[],
})
}
pub(crate) fn semantic_event(&self) -> Option<&crate::document::SemanticEvent> {
self.event.as_ref()
}
pub(crate) fn image(&self) -> Option<&std::sync::Arc<crate::images::Image>> {
self.image.as_ref()
}
pub(crate) fn is_empty_image_fallback(&self) -> bool {
self.empty_image_fallback
}
pub(crate) fn image_density(&self) -> f32 {
self.density
}
pub(crate) fn style(&self) -> &Style {
&self.style
}
pub(crate) fn enclosing_inline(&self) -> &[std::sync::Arc<Style>] {
&self.enclosing_inline
}
pub(super) fn take_enclosing_inline(&mut self) -> Vec<std::sync::Arc<Style>> {
std::mem::take(&mut self.enclosing_inline)
}
pub(super) fn set_enclosing_inline(&mut self, enclosing: Vec<std::sync::Arc<Style>>) {
self.enclosing_inline = enclosing;
}
pub(crate) fn decoration(&self) -> &BoxDecoration {
&self.decoration
}
pub(crate) fn shape_outside(&self) -> &crate::graphics::ShapeOutside {
&self.shape_outside
}
pub(crate) fn children(&self) -> &[BlockContent] {
&self.children
}
pub(super) fn trim_text_boxes(&mut self, requested: [bool; 2]) -> Result<(), DocumentError> {
let requested = if self.initial_letter.is_some_and(|letter| !letter.atomic) {
[true; 2]
} else {
requested
};
let own = self.style.text_box.trim;
if own.contains(&true) {
if self.style.multicol.is_multicol() {
return Err(StyleError::Unsupported(
"text-box-trim on a multi-column container's columns".into(),
)
.into());
}
if self.style.clone_decoration {
return Err(StyleError::Unsupported(
"text-box-trim on each fragment of a box-decoration-break: clone box".into(),
)
.into());
}
}
let display = &self.style.display;
let requested = if display.is_item_container() || display.is_table() {
[false; 2]
} else {
[0, 1].map(|side| own[side] || requested[side])
};
let in_flow: Vec<usize> = self
.children
.iter()
.enumerate()
.filter(|(_, child)| matches!(child, BlockContent::Block(_) | BlockContent::Inline(_)))
.map(|(index, _)| index)
.collect();
let [first, last] = [in_flow.first().copied(), in_flow.last().copied()];
for (index, child) in self.children.iter_mut().enumerate() {
let inherited = [
requested[0] && first == Some(index),
requested[1] && last == Some(index),
];
match child {
BlockContent::Inline(paragraph) => {
paragraph.set_text_box_trim(inherited);
for block in paragraph.anchored_blocks_mut() {
block.trim_text_boxes([false; 2])?;
}
}
BlockContent::Block(block) => {
const TOP: usize = 0;
const BOTTOM: usize = 2;
let open = |side: usize| {
block.style.padding[side].is_zero()
&& block.style.decoration.borders[side].used_width() == 0.0
};
block.trim_text_boxes([
inherited[0] && open(TOP),
inherited[1] && open(BOTTOM),
])?;
}
BlockContent::Positioned(block) => block.trim_text_boxes([false; 2])?,
BlockContent::Events(_) => {}
}
}
Ok(())
}
pub(crate) fn in_flow_children(&self) -> Vec<&BlockContent> {
crate::document::page::in_flow_children(&self.style, &self.children)
}
pub(crate) fn page_boundary(&self) -> &crate::document::PageBoundary {
&self.page
}
pub(crate) fn marker(&self) -> Option<&Paragraph> {
self.marker.as_deref()
}
pub(crate) fn navigation(&self) -> BoxNavigation {
self.navigation
}
pub(crate) fn is_canvas_source(&self) -> bool {
self.canvas_source
}
pub(crate) fn initial_letter(&self) -> Option<&InitialLetterBox> {
self.initial_letter.as_ref()
}
pub(crate) fn is_rendered_legend(&self) -> bool {
self.rendered_legend
}
pub(crate) fn query_container(&self) -> Option<ElementId> {
self.query_container
}
}
pub(crate) struct Traversal<'a> {
document: &'a DocumentTree,
embedded: &'a crate::document::embedded::EmbeddedContent,
root_style: Style,
counters: crate::document::counters::Counters,
navigation: NavigationBuilder,
strings: crate::document::strings::StringAssignments,
generated: crate::document::generated::GeneratedPass,
quotes: crate::style::QuoteDepth,
canvas: BoxDecoration,
canvas_body: Option<ElementId>,
}
struct BlockBuilder<'a, 's, 'c> {
sheet: &'a Stylesheet,
style: &'s Style,
element_page_scope: &'s Option<std::sync::Arc<str>>,
children: &'s mut Vec<BlockContent>,
inline: &'s mut InlineCollector,
run_in: &'s mut Option<RunInSequence>,
first_line: &'s mut FirstLine,
letter: &'s mut Option<OpenLetter>,
ruby: &'s mut crate::document::ruby::RubyStack,
traversal: &'c mut Traversal<'a>,
resources: &'c mut ImageResources<'a>,
}
struct OpenLetter {
outer: InlineCollector,
style: Style,
decoration: BoxDecoration,
navigation: BoxNavigation,
parent: Style,
depth: usize,
}
#[derive(Default)]
struct FirstLine {
origins: Option<std::rc::Rc<[ElementId]>>,
letter: bool,
}
impl FirstLine {
fn of(origins: std::rc::Rc<[ElementId]>) -> Self {
Self {
origins: Some(origins),
letter: true,
}
}
}
struct RunInSequence {
preceding: InlineCollector,
reparented: bool,
anchors: usize,
open: bool,
whitespace: Vec<(String, Style)>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum RunInFollower {
Member,
Block,
Other,
}
pub(crate) struct ImageResources<'a> {
pub base: &'a crate::resources::ResourceBase,
pub resolver: &'a dyn crate::resources::ResourceResolver,
pub cache: &'a mut crate::images::ImageCache,
}
impl ImageResources<'_> {
fn load(
&mut self,
reference: &str,
style: &Style,
) -> Result<std::sync::Arc<crate::images::Image>, crate::images::ImageError> {
self.cache.load_in_namespace(
reference,
self.base,
self.resolver,
style.element_font_namespace(),
)
}
pub(crate) fn shape_outside(&mut self, style: &Style) -> crate::graphics::ShapeOutside {
if style.floating().is_none() {
return crate::graphics::ShapeOutside::None;
}
style
.shape_outside
.load_image(&mut |reference| {
self.cache
.load_decoded(
reference,
self.base,
self.resolver,
style.element_font_namespace(),
)
.ok_or(())
})
.unwrap_or_default()
}
pub(crate) fn backgrounds(&mut self, style: &Style) -> Result<BoxDecoration, DocumentError> {
Ok(style
.decoration
.load_images(|reference| self.load(reference, style))?)
}
}
fn letter_text_error(error: crate::text::TextError) -> DocumentError {
match error {
crate::text::TextError::Font(error) => StyleError::Font(error).into(),
error => DocumentError::Formatting(error.to_string()),
}
}
fn block_axis_edges(style: &Style) -> Result<f32, DocumentError> {
const SIDES: [usize; 2] = [0, 2];
SIDES
.into_iter()
.try_fold(0.0, |sum, side| match style.padding[side] {
crate::style::LengthPercentage::Length(padding) => {
Ok(sum + padding + style.decoration.borders[side].used_width())
}
_ => Err(StyleError::Unsupported(
"percentage block-axis padding on an initial letter sized by it".into(),
)
.into()),
})
}
const SEGMENT_BREAK: &str = "\n";
pub(super) fn inline_pseudo_style(mut style: Style) -> Style {
style.display = Display::Inline;
style.float = crate::style::Float::None;
style.position = crate::style::Position::Static;
style
}
impl<'a> BlockBuilder<'a, '_, '_> {
fn append_text(&mut self, text: &str, style: &Style) -> Result<(), DocumentError> {
if self.ruby.text(self.inline, text, style)? {
return Ok(());
}
if self.ruby.in_annotation() && style.white_space.preserves_breaks() {
for (index, part) in text.split(SEGMENT_BREAK).enumerate() {
if index > 0 {
self.line_break(style)?;
}
self.inline.append(part, style)?;
}
return Ok(());
}
let start = self.first_letter(text, style)?;
self.inline.append(&text[start..], style)
}
fn line_break(&mut self, style: &Style) -> Result<(), DocumentError> {
if self.ruby.in_annotation() {
let mut collapsing = style.clone();
collapsing.white_space.collapse = crate::style::WhiteSpaceCollapse::Collapse;
return self.inline.append(SEGMENT_BREAK, &collapsing);
}
self.inline.line_break(style)
}
fn append_generated(
&mut self,
output: &crate::style::GeneratedOutput,
style: &Style,
) -> Result<(), DocumentError> {
if !output.text().is_empty() {
self.ruby.content(self.inline)?;
}
let leader = output
.leaders()
.first()
.map_or(output.text().len(), |range| range.start);
let start = self.first_letter(&output.text()[..leader], style)?;
self.inline.append_generated_from(output, start, style)
}
fn first_letter(&mut self, text: &str, style: &Style) -> Result<usize, DocumentError> {
if !self.first_line.letter {
return Ok(0);
}
let Some(origins) = self.first_line.origins.clone().filter(|_| {
self.inline.at_line_start()
&& self.run_in.is_none()
&& self.sheet.has_pseudo_rules(PseudoElement::FirstLetter)
}) else {
self.first_line.letter = false;
return Ok(0);
};
let found =
crate::document::first_letter::find(text, style.white_space.collapse, &style.language);
let crate::document::first_letter::FirstLetter::Found {
prefix,
letter,
suffix,
} = found
else {
self.first_line.letter = found == crate::document::first_letter::FirstLetter::Pending;
return Ok(0);
};
self.first_line.letter = false;
self.inline.append(&text[..prefix.start], style)?;
let mut parent = style.clone();
let mut opened = 0;
let mut floated = None;
let mut initial = None;
for &origin in origins.iter() {
let element = self.element(origin);
let pseudo = self.sheet.typographic_pseudo_with_resolver(
element,
&parent,
PseudoElement::FirstLetter,
self.resources.resolver,
)?;
let decoration = self.resources.backgrounds(&pseudo)?;
let outer = std::mem::replace(&mut parent, inline_pseudo_style(pseudo.clone()));
if floated.is_none() && initial.is_none() {
if pseudo.floating().is_some() {
floated = Some((pseudo, decoration, std::mem::take(self.inline), opened));
opened = 0;
continue;
}
if pseudo.initial_letter.is_some() && self.initial_letter_allowed() {
initial = Some((
OpenLetter {
outer: std::mem::take(self.inline),
style: parent.clone(),
decoration,
navigation: self.traversal.navigation.descendant(),
parent: outer,
depth: 0,
},
opened,
));
opened = 0;
continue;
}
}
self.inline.open_box(
&parent,
decoration,
self.traversal.navigation.descendant(),
false,
);
opened += 1;
}
self.first_letter_part(
&origins,
PseudoElement::FirstLetterPrefix,
&parent,
&text[prefix],
)?;
self.inline.append(&text[letter], &parent)?;
self.first_letter_part(
&origins,
PseudoElement::FirstLetterSuffix,
&parent,
&text[suffix.clone()],
)?;
for _ in 0..opened {
self.inline.close_box();
}
if let Some((style, decoration, outer, outer_opened)) = floated {
let contents = std::mem::replace(self.inline, outer);
let children = match contents.finish(&style)? {
Ok(paragraph) => vec![BlockContent::Inline(paragraph)],
Err(stray) => stray,
};
let page_scope =
crate::document::page::used_name(&style.page, self.element_page_scope.as_ref());
let block = BlockBox {
navigation: self.traversal.navigation.descendant(),
..BlockBox::with_decoration(style, children, decoration, page_scope)
};
self.out_of_flow(block);
for _ in 0..outer_opened {
self.inline.close_box();
}
}
if let Some((letter, outer_opened)) = initial {
self.finish_letter(letter, false)?;
for _ in 0..outer_opened {
self.inline.close_box();
}
}
Ok(suffix.end)
}
fn initial_letter_allowed(&self) -> bool {
self.letter.is_none() && self.run_in.is_none() && self.inline.at_first_child()
}
fn open_inline(
&mut self,
style: &Style,
decoration: BoxDecoration,
navigation: BoxNavigation,
canvas_source: bool,
) -> Result<(), DocumentError> {
if style.display.is_ruby() {
return self
.ruby
.open(self.inline, style, decoration, navigation, self.style);
}
self.ruby.inline_box(self.inline)?;
if let Some(letter) = self.letter.as_mut() {
letter.depth += 1;
} else if style.initial_letter.is_some() && self.initial_letter_allowed() {
*self.letter = Some(OpenLetter {
parent: self.inline.open_style().unwrap_or(self.style).clone(),
outer: std::mem::take(self.inline),
style: style.clone(),
decoration,
navigation,
depth: 0,
});
return Ok(());
}
self.inline
.open_box(style, decoration, navigation, canvas_source);
Ok(())
}
fn close_inline(&mut self) -> Result<(), DocumentError> {
if self.ruby.close(self.inline)? == crate::document::ruby::Closed::Ruby {
return Ok(());
}
match self.letter.as_mut() {
Some(letter) if letter.depth > 0 => letter.depth -= 1,
Some(_) => {
let letter = self.letter.take().expect("an open initial letter closes");
return self.finish_letter(letter, false);
}
None => {}
}
self.inline.close_box();
Ok(())
}
fn atomic(&mut self, mut block: BlockBox, parent: &Style) -> Result<(), DocumentError> {
self.ruby.content(self.inline)?;
if block.style.initial_letter.is_none() || !self.initial_letter_allowed() {
return self.inline.atomic(block, parent);
}
let context = crate::text::TextContext::new(&self.sheet.fonts, self.resources.resolver);
let style = &mut block.style;
let initial = style
.initial_letter
.expect("an initial letter has a size and sink");
let surrounding = crate::text::LetterSurrounding::of(
&context,
self.style,
style.initial_letter_align.alignment,
)
.map_err(letter_text_error)?;
if style.height == crate::style::Size::Auto {
let span = surrounding.span(initial.size);
let height = match style.box_sizing {
crate::style::BoxSizing::BorderBox => span,
crate::style::BoxSizing::ContentBox => span - block_axis_edges(style)?,
};
style.height =
crate::style::Size::Value(crate::style::LengthPercentage::Length(height.max(0.0)));
}
block.initial_letter = Some(InitialLetterBox {
surrounding,
atomic: true,
});
self.inline.initial_letter(block, parent, false)
}
fn finish_letter(&mut self, letter: OpenLetter, marker: bool) -> Result<(), DocumentError> {
let OpenLetter {
outer,
mut style,
mut decoration,
navigation,
parent,
..
} = letter;
let mut contents = std::mem::replace(self.inline, outer);
if let Some(origins) = self.first_line.origins.clone()
&& let Some(mut styles) = crate::document::first_line::FirstLineStyles::of(
self.style,
&origins,
self.sheet,
self.traversal.document,
self.resources,
)?
{
let resources = &mut *self.resources;
contents.restyle(
|style| styles.style(style),
|style| resources.backgrounds(style),
)?;
style = styles.style(&style)?;
decoration = self.resources.backgrounds(&style)?;
}
style.text_indent = crate::style::TextIndent::default();
match contents.finish(&style)? {
Ok(paragraph) => {
let block = self.inline_letter_box(style, decoration, navigation, paragraph)?;
self.inline.initial_letter(block, &parent, marker)
}
Err(stray) => {
self.inline.open_box(&style, decoration, navigation, false);
for content in stray {
match content {
BlockContent::Events(events) => {
for event in events {
self.inline.semantic_event(event);
}
}
BlockContent::Positioned(block) => self.inline.anchor(block),
BlockContent::Block(_) | BlockContent::Inline(_) => {
unreachable!("empty inline content holds no flow boxes")
}
}
}
self.inline.close_box();
Ok(())
}
}
}
fn default_summary(&mut self, details: Element<'_>, style: Style) -> Result<(), DocumentError> {
let marker = list_marker(
self.sheet,
details,
&style,
0,
self.traversal,
self.resources,
)?;
self.flush()?;
let outer = std::mem::take(self.inline);
if let Some(marker) = &marker {
self.place_inside_marker(marker)?;
}
self.inline
.append(crate::document::details::DEFAULT_SUMMARY, &style)?;
let content = std::mem::replace(self.inline, outer);
let children = match content.finish(&style)? {
Ok(paragraph) => vec![BlockContent::Inline(paragraph)],
Err(stray) => stray,
};
self.children.push(BlockContent::Block(BlockBox::anonymous(
style,
children,
self.element_page_scope.clone(),
)));
Ok(())
}
fn place_inside_marker(&mut self, marker: &Paragraph) -> Result<(), DocumentError> {
let style = marker.style();
let navigation = self.traversal.navigation.descendant();
let letter =
(style.initial_letter.is_some() && self.initial_letter_allowed()).then(|| OpenLetter {
parent: self.inline.open_style().unwrap_or(self.style).clone(),
outer: std::mem::take(self.inline),
style: style.clone(),
decoration: BoxDecoration::default(),
navigation,
depth: 0,
});
if letter.is_none() {
self.inline.open_marker(style, navigation);
}
if let Some(image) = marker.marker_image() {
let [width, height] = marker.marker_image_size().expect("image marker has size");
let mut box_style = style.anonymous(Display::InlineBlock);
box_style.width =
crate::style::Size::Value(crate::style::LengthPercentage::Length(width));
box_style.height =
crate::style::Size::Value(crate::style::LengthPercentage::Length(height));
let mut decoration = BoxDecoration::default();
std::sync::Arc::make_mut(&mut decoration.backgrounds).images = vec![image.clone()];
let atomic = BlockBox::with_decoration(
box_style,
Vec::new(),
decoration,
self.element_page_scope.clone(),
);
self.inline.atomic(atomic, style)?;
}
self.inline.append(marker.text(), style)?;
if let Some(letter) = letter {
return self.finish_letter(letter, true);
}
self.inline.close_marker();
Ok(())
}
fn inline_letter_box(
&mut self,
mut style: Style,
decoration: BoxDecoration,
navigation: BoxNavigation,
mut paragraph: Paragraph,
) -> Result<BlockBox, DocumentError> {
let context = crate::text::TextContext::new(&self.sheet.fonts, self.resources.resolver);
let surrounding = crate::text::LetterSurrounding::of(
&context,
self.style,
style.initial_letter_align.alignment,
)
.map_err(letter_text_error)?;
let edges = if style.initial_letter_align.border_box {
block_axis_edges(&style)?
} else {
0.0
};
let (scale, aligned) = crate::text::initial_letter_scale(
&context,
&surrounding,
paragraph.style(),
paragraph.text(),
edges,
)
.map_err(letter_text_error)?;
paragraph.size_initial_letter(scale, aligned);
style.display = Display::InlineBlock;
let page_scope =
crate::document::page::used_name(&style.page, self.element_page_scope.as_ref());
Ok(BlockBox {
navigation,
initial_letter: Some(InitialLetterBox {
surrounding,
atomic: false,
}),
..BlockBox::with_decoration(
style,
vec![BlockContent::Inline(paragraph)],
decoration,
page_scope,
)
})
}
fn first_letter_part(
&mut self,
origins: &[ElementId],
pseudo: PseudoElement,
parent: &Style,
text: &str,
) -> Result<(), DocumentError> {
if text.is_empty() {
return Ok(());
}
if !self.sheet.has_pseudo_rules(pseudo) {
return self.inline.append(text, parent);
}
let mut parent = parent.clone();
for &origin in origins {
let element = self.element(origin);
parent = inline_pseudo_style(self.sheet.typographic_pseudo_with_resolver(
element,
&parent,
pseudo,
self.resources.resolver,
)?);
let decoration = self.resources.backgrounds(&parent)?;
self.inline.open_box(
&parent,
decoration,
self.traversal.navigation.descendant(),
false,
);
}
self.inline.append(text, &parent)?;
for _ in origins {
self.inline.close_box();
}
Ok(())
}
fn element(&self, id: ElementId) -> Element<'a> {
self.traversal
.document
.element(id)
.expect("first-line origins belong to the formatted document")
}
fn finish_inline(
&mut self,
collected: InlineCollector,
style: &Style,
origins: Option<&[ElementId]>,
) -> Result<Result<Paragraph, Vec<BlockContent>>, DocumentError> {
let (sheet, document) = (self.sheet, self.traversal.document);
let resources = &mut *self.resources;
collected.finish_with_first_line(style, |paragraph| match origins {
Some(origins) => {
crate::document::first_line::variant(paragraph, origins, sheet, document, resources)
}
None => Ok(None),
})
}
fn flush(&mut self) -> Result<(), DocumentError> {
if self.letter.is_some() {
return Err(StyleError::Unsupported(
"block-level content inside an initial letter".into(),
)
.into());
}
if self.ruby.holds_explicit() {
return Err(StyleError::Unsupported(
"block-level content inside a ruby container".into(),
)
.into());
}
self.ruby.finish(self.inline)?;
let collected = self.inline.split();
let origins = self.first_line.origins.clone();
let origins = origins.as_deref();
match self.finish_inline(collected, self.style, origins)? {
Ok(mut paragraph) => {
let first = !self
.children
.iter()
.any(|child| matches!(child, BlockContent::Block(_) | BlockContent::Inline(_)));
paragraph.set_formatted_lines(first, false);
*self.first_line = FirstLine::default();
self.children.push(BlockContent::Inline(paragraph));
}
Err(stray) => self.children.extend(stray),
}
Ok(())
}
fn child_first_line(&mut self, element: ElementId, display: &Display) -> FirstLine {
let inherited = std::mem::take(self.first_line);
let own = || std::rc::Rc::from([element]);
if !display.is_block_level_block_container() {
return if display.is_block_container() {
FirstLine::of(own())
} else {
FirstLine::default()
};
}
match inherited.origins {
Some(origins) => FirstLine {
origins: Some(origins.iter().copied().chain([element]).collect()),
letter: inherited.letter,
},
None => FirstLine::of(own()),
}
}
fn begin_run_in(&mut self) -> Result<(), DocumentError> {
self.close_run_in();
let sequence = self.run_in.get_or_insert_with(|| RunInSequence {
preceding: std::mem::take(self.inline),
reparented: false,
anchors: 0,
open: false,
whitespace: Vec::new(),
});
sequence.open = true;
for (text, style) in std::mem::take(&mut sequence.whitespace) {
self.inline.append(&text, &style)?;
}
Ok(())
}
fn defer_run_in_whitespace(&mut self, text: &str, style: &Style) -> bool {
self.close_run_in();
let Some(sequence) = self.run_in.as_mut() else {
return false;
};
sequence.whitespace.push((text.to_owned(), style.clone()));
true
}
fn close_run_in(&mut self) {
if let Some(sequence) = self.run_in.as_mut().filter(|sequence| sequence.open) {
sequence.anchors = self.inline.anchor_count();
sequence.open = false;
}
}
fn resolve_run_in(
&mut self,
follower: RunInFollower,
) -> Result<Option<InlineCollector>, DocumentError> {
if follower == RunInFollower::Member {
return Ok(None);
}
self.close_run_in();
let Some(sequence) = self.run_in.take() else {
return Ok(None);
};
let mut collected = std::mem::replace(self.inline, sequence.preceding);
if follower == RunInFollower::Block {
let following = collected.take_anchors_after(sequence.anchors);
for block in following {
self.out_of_flow(block);
}
return Ok(Some(collected));
}
if sequence.reparented {
self.inline.extend(collected)?;
} else {
self.flush()?;
*self.inline = collected;
}
for (text, style) in sequence.whitespace {
self.inline.append(&text, &style)?;
}
Ok(None)
}
fn out_of_flow(&mut self, block: BlockBox) {
if let Some(base) = self.ruby.base_level() {
base.anchor(block);
} else if self.style.display.is_item_container() || self.inline.is_between_blocks() {
self.children.push(BlockContent::Positioned(block));
} else {
self.inline.anchor(block);
}
}
fn generated(
&mut self,
element: Element<'_>,
parent: &Style,
pseudo: GeneratedPseudoElement,
) -> Result<(), DocumentError> {
let Some((mut style, content)) = self.sheet.pseudo_with_resolver(
element,
parent,
pseudo.into(),
self.resources.resolver,
)?
else {
return Ok(());
};
let element_page_scope =
crate::document::page::used_name(&parent.page, self.element_page_scope.as_ref());
validate_box(&style)?;
normalize_child_display(&mut style.display, false, &self.style.display);
let block_child = std::ptr::eq(parent, self.style);
if let Some(inner) = style.display.run_in().cloned() {
if block_child {
self.begin_run_in()?;
}
style.display = inner;
} else if block_child {
self.resolve_run_in(
if style.position.is_out_of_flow() || style.floating().is_some() {
RunInFollower::Member
} else {
RunInFollower::Other
},
)?;
}
let decoration = if style.display == Display::Contents {
BoxDecoration::default()
} else {
self.resources.backgrounds(&style)?
};
self.traversal.counters.prepare(
&style.counters,
self.traversal.document,
self.sheet,
&self.traversal.root_style,
self.resources.resolver,
)?;
self.traversal.counters.enter(
crate::style::PageStyleTarget {
element: element.id(),
pseudo: Some(pseudo.into()),
},
&style.counters,
&style.display,
style.containment().style,
)?;
let context = crate::style::PageStyleTarget {
element: element.id(),
pseudo: Some(pseudo.into()),
};
let event = content
.named_string_requests()
.next()
.is_some()
.then(|| self.traversal.strings.generated_event(element, pseudo));
let bound = self.traversal.generated.bind(&content, context)?;
let output = bound.element_output_with_counters(
crate::document::MAX_INLINE_TEXT_BYTES,
&mut |request| self.traversal.counters.text(request),
&style.quotes,
&mut self.traversal.quotes,
)?;
let text = output.text();
self.traversal.counters.leave();
self.traversal
.generated
.generated(element, pseudo, text, &style);
self.traversal
.navigation
.generated(element, pseudo, text, &style);
self.traversal
.strings
.generated(element, pseudo, text, &style);
if style.display != Display::Contents
&& (style.position.is_out_of_flow() || style.floating().is_some())
{
let children = Paragraph::generated_output(&output, &style)?
.into_iter()
.map(BlockContent::Inline)
.collect();
let shape_outside = self.resources.shape_outside(&style);
let mut generated = self.generated_block(
style,
children,
decoration,
element_page_scope.as_ref(),
event,
);
generated.shape_outside = shape_outside;
self.out_of_flow(generated);
return Ok(());
}
match &style.display {
Display::Contents => {
if let Some(event) = event {
self.inline.semantic_event(event);
}
self.append_generated(&output, &style)?;
}
Display::Inline
| Display::Ruby
| Display::RubyBase
| Display::RubyText
| Display::RubyBaseContainer
| Display::RubyTextContainer => {
if let Some(event) = event {
self.inline.semantic_event(event);
}
self.open_inline(
&style,
decoration,
self.traversal.navigation.descendant(),
false,
)?;
self.append_generated(&output, &style)?;
self.close_inline()?;
}
Display::InlineBlock
| Display::InlineFlex
| Display::InlineGrid
| Display::InlineTable => {
let children = Paragraph::generated_output(&output, &style)?
.into_iter()
.map(BlockContent::Inline)
.collect();
let atomic = self.generated_block(
style.clone(),
children,
decoration,
element_page_scope.as_ref(),
event,
);
self.atomic(atomic, parent)?;
}
Display::Unsupported(value) => {
return Err(StyleError::Unsupported(format!("generated display: {value}")).into());
}
Display::ListItem
| Display::FlowRootListItem
| Display::InlineListItem
| Display::InlineFlowRootListItem => {
return Err(DocumentError::Formatting(
"generated list-item counters are not supported".into(),
));
}
Display::None => unreachable!("hidden pseudo-elements are excluded by the cascade"),
_ => {
self.flush()?;
if style.display == Display::BlockRuby {
style.display = Display::Block;
}
let first_line = std::mem::take(self.first_line);
let children = if style.display.is_block_level_block_container() {
self.first_line_block(first_line, &output, &style)?
} else {
Paragraph::generated_output(&output, &style)?
.into_iter()
.map(BlockContent::Inline)
.collect()
};
let mut generated = self.generated_block(
style,
children,
decoration,
element_page_scope.as_ref(),
event,
);
generated.enclosing_inline = self.inline.open_boxes();
self.children.push(BlockContent::Block(generated));
}
}
Ok(())
}
fn first_line_block(
&mut self,
first_line: FirstLine,
output: &crate::style::GeneratedOutput,
style: &Style,
) -> Result<Vec<BlockContent>, DocumentError> {
let outer = std::mem::take(self.inline);
let origins = first_line.origins.clone();
*self.first_line = first_line;
let appended = self.append_generated(output, style);
let contents = std::mem::replace(self.inline, outer);
*self.first_line = FirstLine::default();
appended?;
Ok(
match self.finish_inline(contents, style, origins.as_deref())? {
Ok(paragraph) => vec![BlockContent::Inline(paragraph)],
Err(stray) => stray,
},
)
}
fn generated_block(
&self,
style: Style,
children: Vec<BlockContent>,
decoration: BoxDecoration,
element_page_scope: Option<&std::sync::Arc<str>>,
event: Option<crate::document::SemanticEvent>,
) -> BlockBox {
let page_scope = crate::document::page::used_name(&style.page, element_page_scope);
BlockBox {
navigation: self.traversal.navigation.descendant(),
canvas_source: false,
event,
..BlockBox::with_decoration(style, children, decoration, page_scope)
}
}
}
fn validate_box(style: &Style) -> Result<(), StyleError> {
style.display.validate()?;
if let Some(reference) = &style.svg.clip_reference {
return Err(StyleError::Unsupported(format!(
"clip-path reference to an SVG clipPath element on a box: {reference}"
)));
}
Ok(())
}
fn unsupported_element(tag: &str) -> bool {
matches!(tag, "math")
}
pub(super) fn is_replaced(element: Element<'_>) -> bool {
match element.name() {
"svg" => true,
"img" | "iframe" | "embed" | "video" | "audio" => {
element.namespace() == crate::dom::HTML_NAMESPACE
}
"object" => element.namespace() == crate::dom::HTML_NAMESPACE && element.object_embeds(),
_ => false,
}
}
fn list_marker(
sheet: &Stylesheet,
element: Element<'_>,
style: &Style,
ordinal: i128,
traversal: &mut Traversal<'_>,
resources: &mut ImageResources<'_>,
) -> Result<Option<Paragraph>, DocumentError> {
if !style.display.is_list_item() {
return Ok(None);
}
let Some((marker, content)) = sheet.marker_with_resolver(element, style, resources.resolver)?
else {
return Ok(None);
};
let used = crate::document::lists::used_style(&marker);
let Some(content) = content else {
return crate::document::lists::marker(style, &used, ordinal, resources);
};
let bound = traversal.generated.bind(
&content,
crate::style::PageStyleTarget {
element: element.id(),
pseudo: Some(PseudoElement::Marker),
},
)?;
let output = bound.element_output_with_counters(
crate::document::MAX_INLINE_TEXT_BYTES,
&mut |request| traversal.counters.text(request),
&marker.quotes,
&mut traversal.quotes,
)?;
Paragraph::generated_marker(&output, &used)
}
pub(super) fn normalize_child_display(display: &mut Display, replaced: bool, parent: &Display) {
if replaced && let Display::RunIn(inner) = display {
normalize_child_display(inner, true, &Display::Block);
} else if replaced && *display == Display::BlockRuby {
*display = Display::Block;
} else if replaced
&& (display.is_table_internal()
|| display.is_ruby()
|| display.is_atomic_inline()
|| matches!(
display,
Display::Table
| Display::TableCaption
| Display::Flex
| Display::Grid
| Display::ListItem
| Display::FlowRootListItem
| Display::InlineListItem
))
{
*display = Display::Inline;
}
if parent.is_item_container() && display.is_inline_level() {
*display = display.blockified();
}
}
pub(super) fn normalize_root_display(display: &mut Display) {
*display = if *display == Display::Contents {
Display::Block
} else {
display.blockified()
};
}
fn computed_style(
sheet: &Stylesheet,
element: Element<'_>,
parent: &Style,
resolver: &dyn crate::resources::ResourceResolver,
) -> Result<Box<Style>, DocumentError> {
sheet
.computed_with_resolver(element, parent, resolver)
.map(Box::new)
.map_err(Into::into)
}
#[derive(Clone, Copy)]
enum Placement {
Root,
Flow,
Positioned,
Atomic,
}
struct OpenBlock {
decoration: BoxDecoration,
shape_outside: crate::graphics::ShapeOutside,
children: Vec<BlockContent>,
inline: InlineCollector,
marker: Option<Paragraph>,
image: Option<std::sync::Arc<crate::images::Image>>,
density: f32,
navigation: BoxNavigation,
placement: Placement,
event: Option<crate::document::SemanticEvent>,
run_in: Option<RunInSequence>,
pending_run_in: Option<InlineCollector>,
first_line: FirstLine,
letter: Option<OpenLetter>,
ruby: crate::document::ruby::RubyStack,
ruby_container: bool,
}
struct Frame<'d> {
element: Element<'d>,
style: Box<Style>,
page_scope: Option<std::sync::Arc<str>>,
depth: usize,
nodes: Option<ChildNodes<'d>>,
leading: Option<crate::dom::Node<'d>>,
block: Option<OpenBlock>,
started: bool,
quotes: Option<crate::style::QuoteDepth>,
generated: bool,
ordinal: i128,
}
impl<'d> Frame<'d> {
fn new(
element: Element<'d>,
style: Box<Style>,
depth: usize,
ordinal: i128,
placement: Option<Placement>,
ancestor_page: Option<&std::sync::Arc<str>>,
) -> Self {
let page_scope = crate::document::page::used_name(&style.page, ancestor_page);
Self {
element,
style,
page_scope,
depth,
nodes: None,
leading: None,
block: placement.map(|placement| OpenBlock {
decoration: BoxDecoration::default(),
shape_outside: crate::graphics::ShapeOutside::None,
children: Vec::new(),
inline: InlineCollector::default(),
marker: None,
image: None,
density: DEFAULT_DENSITY,
navigation: BoxNavigation::default(),
placement,
event: None,
run_in: None,
pending_run_in: None,
first_line: FirstLine::default(),
letter: None,
ruby: crate::document::ruby::RubyStack::default(),
ruby_container: false,
}),
started: false,
quotes: None,
generated: false,
ordinal,
}
}
}
fn active_builder<'a, 's, 'c>(
frames: &'s mut [Frame<'_>],
index: usize,
sheet: &'a Stylesheet,
traversal: &'c mut Traversal<'a>,
resources: &'c mut ImageResources<'a>,
) -> (BlockBuilder<'a, 's, 'c>, &'s Style) {
let (frame, descendants) = frames[index..].split_first_mut().unwrap();
let style = descendants
.last()
.map_or(&*frame.style, |frame| &frame.style);
let element_page_scope = descendants
.last()
.map_or(&frame.page_scope, |frame| &frame.page_scope);
let block = frame.block.as_mut().unwrap();
(
BlockBuilder {
sheet,
style: &frame.style,
element_page_scope,
children: &mut block.children,
inline: &mut block.inline,
run_in: &mut block.run_in,
first_line: &mut block.first_line,
letter: &mut block.letter,
ruby: &mut block.ruby,
traversal,
resources,
},
style,
)
}
fn block<'a>(
element: Element<'_>,
style: Box<Style>,
sheet: &'a Stylesheet,
depth: usize,
ordinal: i128,
traversal: &mut Traversal<'a>,
resources: &mut ImageResources<'a>,
) -> Result<BlockBox, DocumentError> {
let mut frames = vec![Frame::new(
element,
style,
depth,
ordinal,
Some(Placement::Root),
None,
)];
if frames[0].style.display.is_block_container() {
frames[0]
.block
.as_mut()
.expect("the root frame is a block")
.first_line = FirstLine::of(std::rc::Rc::from([element.id()]));
}
let mut blocks = vec![0];
loop {
let index = frames.len() - 1;
let block_index = *blocks.last().unwrap();
if !frames[index].started {
let frame = &mut frames[index];
let element = frame.element;
frame.quotes = frame.style.containment().style.then_some(traversal.quotes);
traversal.generated.capture(element, &traversal.counters);
if let Some(block) = &mut frame.block {
let skips = frame.style.skips_contents() && frame.style.containment().layout;
block.decoration = resources.backgrounds(&frame.style)?;
block.shape_outside = resources.shape_outside(&frame.style);
if index == 0 {
traversal.canvas = background_only(&block.decoration);
}
let control = if skips {
None
} else if let Some(frameset) = crate::document::frameset::content(
element,
&frame.style,
sheet,
traversal.embedded,
frame.page_scope.as_ref(),
) {
Some(frameset)
} else {
crate::document::controls::content(
element,
&frame.style,
sheet,
resources,
frame.page_scope.as_ref(),
)?
};
let rendered_control = control.is_some();
block.image = if let Some(control) = control {
block.children.extend(control.children);
control.image
} else {
match element.name() {
"img" => {
let image = sheet.image_source(element).and_then(|source| {
block.density = source.density;
resources.cache.load_optional(
&source.url,
resources.base,
resources.resolver,
frame.style.element_font_namespace(),
)
});
if image.is_none()
&& !skips
&& let Some(alt) = element.attr("alt")
{
block.inline.append(alt, &frame.style)?;
}
image
}
"svg" => Some(resources.cache.inline_svg_in_namespace(
crate::document::svg::serialize(
element,
&frame.style,
&crate::document::svg::Styling {
sheet,
resolver: resources.resolver,
},
)?,
resources.base,
resources.resolver,
frame.style.element_font_namespace(),
)?),
"video" if is_replaced(element) => Some(crate::document::media::poster(
element,
&frame.style,
resources,
)),
"audio" if is_replaced(element) => Some(
crate::document::media::audio_controls(&frame.style, resources)?,
),
_ if is_replaced(element) => traversal.embedded.content(element.id()).map(
|embedded| match embedded {
crate::document::embedded::Embedded::Image(image) => image.clone(),
crate::document::embedded::Embedded::Navigable(navigable) => {
std::sync::Arc::new(crate::images::Image::Frame(
navigable.clone(),
sheet.used_color_scheme(&frame.style.color_scheme),
))
}
},
),
_ => None,
}
};
block.marker = if skips {
None
} else {
list_marker(
sheet,
element,
&frame.style,
frame.ordinal,
traversal,
resources,
)?
};
let assignment = traversal.strings.record(
element,
&frame.style.string_set,
&mut traversal.counters,
block.marker.as_ref().map(Paragraph::text),
)?;
block.event = Some(traversal.strings.event(element, assignment, true));
block.navigation = traversal.navigation.enter(element);
traversal.navigation.record(
element,
&frame.style,
block.marker.as_ref().map(Paragraph::text),
traversal.quotes,
if frame.style.bookmark.level.is_some() {
traversal.counters.snapshot(&frame.style.bookmark.label)?
} else {
Default::default()
},
&mut block.navigation,
);
if frame.style.display == Display::BlockRuby {
frame.style.display = Display::Block;
block.ruby_container = true;
}
let inside_marker = frame
.style
.has_inside_marker()
.then(|| block.marker.take())
.flatten();
if let Some(marker) = inside_marker {
let (mut builder, _) =
active_builder(&mut frames, index, sheet, traversal, resources);
builder.place_inside_marker(&marker)?;
}
let frame = &mut frames[index];
let block = frame.block.as_mut().expect("a block frame builds a block");
if let Some(run_in) = block.pending_run_in.take() {
block.run_in = Some(RunInSequence {
preceding: std::mem::replace(&mut block.inline, run_in),
reparented: true,
anchors: block.inline.anchor_count(),
open: false,
whitespace: Vec::new(),
});
}
if block.ruby_container {
let container = crate::document::ruby::anonymous(&frame.style, Display::Ruby);
block.ruby.open(
&mut block.inline,
&container,
BoxDecoration::default(),
BoxNavigation::default(),
&frame.style,
)?;
}
frame.generated = !skips
&& !rendered_control
&& block.image.is_none()
&& frame.style.display != Display::TableColumn;
} else {
let marker = list_marker(
sheet,
element,
&frame.style,
frame.ordinal,
traversal,
resources,
)?;
let assignment = traversal.strings.record(
element,
&frame.style.string_set,
&mut traversal.counters,
marker.as_ref().map(Paragraph::text),
)?;
let event = traversal.strings.event(element, assignment, true);
let mut navigation = traversal.navigation.enter(element);
traversal.navigation.record(
element,
&frame.style,
marker.as_ref().map(Paragraph::text),
traversal.quotes,
if frame.style.bookmark.level.is_some() {
traversal.counters.snapshot(&frame.style.bookmark.label)?
} else {
Default::default()
},
&mut navigation,
);
let canvas_source = index == 0 || traversal.canvas_body == Some(element.id());
let (mut builder, style) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
builder.inline.semantic_event(event);
if style.display == Display::Contents {
builder.inline.open_contents(navigation.link);
} else {
let decoration = builder.resources.backgrounds(style)?;
builder.open_inline(style, decoration, navigation, canvas_source)?;
if let Some(marker) = marker {
builder.place_inside_marker(&marker)?;
}
}
frames[index].generated = true;
}
if frames[index].generated || element.name() == "br" {
if frames[index].depth > MAX_FORMATTING_DEPTH {
return Err(DocumentError::Formatting(format!(
"{FORMATTING_NESTING_RESOURCE} exceeds {MAX_FORMATTING_DEPTH}"
)));
}
let (mut builder, style) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
builder.generated(element, style, GeneratedPseudoElement::Before)?;
if element.name() == "br" {
builder.line_break(style)?;
builder.generated(element, style, GeneratedPseudoElement::After)?;
frames[index].generated = false;
} else {
if element.namespace() == crate::dom::HTML_NAMESPACE && element.name() == "wbr"
{
builder.inline.optional_break(style);
}
if let Some(summary) =
crate::document::details::default_summary_style(element, style)
{
builder.default_summary(element, summary)?;
}
frames[index].nodes = Some(element.child_nodes(TreeRelation::Formatting));
frames[index].leading = crate::document::details::summary(element);
}
}
frames[index].started = true;
continue;
}
let leading = frames[index].leading.take();
if let Some(node) =
leading.or_else(|| frames[index].nodes.as_mut().and_then(Iterator::next))
{
if leading.is_none()
&& !crate::document::details::renders_child(frames[index].element, node)
{
continue;
}
let block_child = frames[block_index + 1..=index]
.iter()
.all(|frame| frame.style.display == Display::Contents);
if let Some(text) = node.value().as_text() {
let (mut builder, style) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
if block_child {
if text.chars().all(|ch| {
crate::document::inline::collapses_character(ch, style.white_space.collapse)
}) {
if builder.defer_run_in_whitespace(text, style) {
continue;
}
} else {
builder.resolve_run_in(RunInFollower::Other)?;
}
}
builder.append_text(text, style)?;
continue;
}
let Some(child) = node.element() else {
continue;
};
let parent = &frames[index].style;
let mut child_style = computed_style(sheet, child, parent, resources.resolver)?;
if traversal.canvas_body == Some(child.id()) {
traversal.canvas = if child_style.display == Display::None {
BoxDecoration::default()
} else {
background_only(&resources.backgrounds(&child_style)?)
};
}
validate_box(&child_style)?;
let replaced = is_replaced(child);
normalize_child_display(
&mut child_style.display,
replaced,
&frames[block_index].style.display,
);
crate::document::controls::used_style(child, &mut child_style);
crate::document::frameset::used_style(child, &mut child_style, sheet);
if frames[block_index].style.display == Display::TableColumnGroup
&& child_style.display != Display::Contents
&& child_style.display != Display::TableColumn
{
continue;
}
if child_style.display == Display::None {
let mut events = Vec::new();
sheet.with_document_values(
traversal.document,
&traversal.root_style,
resources.resolver,
|styles| {
traversal.counters.visit_hidden(
child,
styles,
|element, assignments, counters| {
traversal.generated.capture(element, counters);
let assignment = traversal.strings.record(
element,
assignments,
counters,
None,
)?;
if assignment.is_some() {
events
.push(traversal.strings.event(element, assignment, false));
}
Ok(())
},
)
},
)?;
let (builder, _) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
for event in events {
builder.inline.semantic_event(event);
}
continue;
}
if child_style.display != Display::Contents && unsupported_element(child.name()) {
return Err(DocumentError::Formatting(format!(
"unsupported formatting element: {}",
child.name()
)));
}
traversal.counters.prepare(
&child_style.counters,
traversal.document,
sheet,
&traversal.root_style,
resources.resolver,
)?;
traversal.counters.enter(
crate::style::PageStyleTarget {
element: child.id(),
pseudo: None,
},
&child_style.counters,
&child_style.display,
child_style.containment().style,
)?;
let child_depth = frames[index].depth + 1;
let ancestor_page = frames[index].page_scope.clone();
let (mut builder, _) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
let run_in = child_style.display.run_in().cloned();
let merged = if !block_child {
None
} else if run_in.is_some() {
builder.begin_run_in()?;
None
} else {
builder.resolve_run_in(
if child_style.display == Display::Contents
|| child_style.position.is_out_of_flow()
|| child_style.floating().is_some()
{
RunInFollower::Member
} else if matches!(child_style.display, Display::Block | Display::ListItem)
&& !replaced
&& !child_style.establishes_formatting_context()
{
RunInFollower::Block
} else {
RunInFollower::Other
},
)?
};
if let Some(inner) = run_in {
child_style.display = inner;
}
let placement = if child_style.display == Display::Contents {
None
} else if child_style.position.is_out_of_flow() || child_style.floating().is_some() {
Some(Placement::Positioned)
} else {
match &child_style.display {
Display::None => unreachable!("hidden elements are skipped before traversal"),
Display::Contents => unreachable!("boxless elements have no placement"),
Display::Block
| Display::FlowRoot
| Display::Flex
| Display::Grid
| Display::ListItem
| Display::FlowRootListItem
| Display::Table
| Display::TableRowGroup
| Display::TableHeaderGroup
| Display::TableFooterGroup
| Display::TableRow
| Display::TableCell
| Display::TableColumn
| Display::TableColumnGroup
| Display::TableCaption => {
builder.flush()?;
Some(Placement::Flow)
}
Display::InlineBlock
| Display::InlineFlex
| Display::InlineGrid
| Display::InlineTable
| Display::InlineFlowRootListItem => Some(Placement::Atomic),
Display::RunIn(_) => unreachable!("run-in boxes take their inner display"),
Display::Inline if replaced => Some(Placement::Atomic),
Display::InlineListItem
| Display::Ruby
| Display::RubyBase
| Display::RubyText
| Display::RubyBaseContainer
| Display::RubyTextContainer => None,
Display::BlockRuby => {
builder.flush()?;
Some(Placement::Flow)
}
Display::Inline => {
if child.name() == "br" {
builder
.traversal
.generated
.capture(child, &builder.traversal.counters);
let assignment = builder.traversal.strings.record(
child,
&child_style.string_set,
&mut builder.traversal.counters,
None,
)?;
builder.inline.semantic_event(
builder.traversal.strings.event(child, assignment, true),
);
builder.generated(
child,
&child_style,
GeneratedPseudoElement::Before,
)?;
builder.line_break(&child_style)?;
builder.generated(
child,
&child_style,
GeneratedPseudoElement::After,
)?;
builder.traversal.counters.leave();
continue;
}
None
}
Display::Unsupported(value) => {
return Err(StyleError::Unsupported(format!(
"display {value} on {}",
child.name()
))
.into());
}
}
};
let ordinal = if child_style.display.is_list_item() {
builder.traversal.counters.ordinal()?
} else {
0
};
let first_line = match placement {
Some(Placement::Flow) => builder.child_first_line(child.id(), &child_style.display),
Some(_) if child_style.display.is_block_container() => {
FirstLine::of(std::rc::Rc::from([child.id()]))
}
_ => FirstLine::default(),
};
if placement.is_some() {
blocks.push(frames.len());
}
frames.push(Frame::new(
child,
child_style,
child_depth,
ordinal,
placement,
ancestor_page.as_ref(),
));
if let Some(block) = frames.last_mut().and_then(|frame| frame.block.as_mut()) {
block.first_line = first_line;
}
if let Some(run_in) = merged {
frames
.last_mut()
.and_then(|frame| frame.block.as_mut())
.expect("a block box takes the run-in sequence")
.pending_run_in = Some(run_in);
}
continue;
}
let element = frames[index].element;
let generated = frames[index].generated;
let contents = frames[index].style.display == Display::Contents;
let quotes = frames[index].quotes;
let (mut builder, style) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
if generated {
builder.generated(element, style, GeneratedPseudoElement::After)?;
}
if let Some(depth) = quotes {
builder.traversal.quotes = depth;
}
if index != block_index {
if contents {
builder.inline.close_contents();
} else {
builder.close_inline()?;
}
builder.traversal.navigation.leave();
frames.pop();
traversal.counters.leave();
continue;
}
builder.resolve_run_in(RunInFollower::Other)?;
if frames[index]
.block
.as_ref()
.is_some_and(|block| block.ruby_container)
{
let (builder, _) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
builder.ruby.close(builder.inline)?;
}
let (mut builder, _) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
builder.flush()?;
let frame = &mut frames[index];
let block = frame.block.as_mut().unwrap();
if block.marker.is_some() && block.children.is_empty() {
block.inline.line_break(&frame.style)?;
let (mut builder, _) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
builder.flush()?;
}
traversal.navigation.leave();
let frame = frames.pop().unwrap();
blocks.pop();
let mut state = frame.block.unwrap();
if let Some(BlockContent::Inline(paragraph)) = state
.children
.iter_mut()
.rfind(|child| matches!(child, BlockContent::Block(_) | BlockContent::Inline(_)))
{
paragraph.set_formatted_lines(paragraph.first_formatted_line(), true);
}
let canvas_source = index == 0 || traversal.canvas_body == Some(element.id());
let rendered_legend = crate::document::controls::is_rendered_legend(element, &frame.style);
let (style, children) = crate::document::controls::fieldset(
element,
*frame.style,
state.children,
frame.page_scope.as_ref(),
);
let mut block =
BlockBox::with_decoration(style, children, state.decoration, frame.page_scope);
block.rendered_legend = rendered_legend;
block.marker = state.marker.map(Box::new);
block.shape_outside = state.shape_outside;
block.image = state.image;
block.empty_image_fallback = element.namespace() == crate::dom::HTML_NAMESPACE
&& element.name() == "img"
&& element.attr("alt") == Some("")
&& block.image.is_none();
block.density = state.density;
block.navigation = state.navigation;
block.event = state.event;
block.canvas_source = canvas_source;
block.query_container = block
.style
.containment()
.query_container
.then(|| element.id());
if matches!(state.placement, Placement::Root) {
return Ok(block);
}
let (mut builder, parent) = active_builder(
&mut frames,
*blocks.last().unwrap(),
sheet,
traversal,
resources,
);
match state.placement {
Placement::Flow => {
block.enclosing_inline = builder.inline.open_boxes();
builder.children.push(BlockContent::Block(block));
}
Placement::Positioned => builder.out_of_flow(block),
Placement::Atomic => builder.atomic(block, parent)?,
Placement::Root => unreachable!("root returned before attaching to a parent"),
}
traversal.counters.leave();
}
}
pub(crate) struct Input<'a> {
pub html: &'a DocumentTree,
pub embedded: &'a crate::document::embedded::EmbeddedContent,
pub images: &'a std::rc::Rc<std::cell::RefCell<crate::images::ImageCache>>,
}
pub(crate) fn build(
input: &Input<'_>,
sheet: &mut Stylesheet,
base: &crate::resources::ResourceBase,
resolver: &dyn crate::resources::ResourceResolver,
navigation: NavigationBuilder,
values: crate::document::generated::GeneratedValues,
) -> Result<Formatted, DocumentError> {
let Input {
html,
embedded,
images,
} = *input;
sheet.anchor_nodes.borrow_mut().clear();
let mut generated =
crate::document::generated::GeneratedPass::new(navigation.targets.clone(), values);
let element = html.root_element();
let mut style = sheet
.resolve_document_root_with_pages(
html,
resolver,
&|styles| crate::document::first_page::select_name(html, styles, &generated),
&|styles| crate::document::first_page::select_side(html, styles, &generated),
)
.map_err(|error| match error {
StyleError::GrammarLimit {
resource: FORMATTING_NESTING_RESOURCE,
limit,
} => {
DocumentError::Formatting(format!("{FORMATTING_NESTING_RESOURCE} exceeds {limit}"))
}
error => DocumentError::Style(error),
})?;
let sheet = &*sheet;
let mut cache = images.borrow_mut();
let mut resources = ImageResources {
base,
resolver,
cache: &mut cache,
};
let area = sheet.page_content_box();
let resolved = sheet.resolve_page(
&style,
sheet.first_page_request().clone(),
Some([area.width, area.height]),
resolver,
)?;
let bindings = generated.bindings();
let page = PageBox::load(resolved, &mut resources, &bindings)?;
validate_box(&style)?;
if style.display == Display::None {
let mut strings = crate::document::strings::StringAssignments::new(html);
let mut counters = crate::document::counters::Counters::default();
let mut events = Vec::new();
sheet.with_document_values(html, &style, resolver, |styles| {
counters.visit_hidden(element, styles, |element, assignments, counters| {
generated.capture(element, counters);
let assignment = strings.record(element, assignments, counters, None)?;
if assignment.is_some() {
events.push(strings.event(element, assignment, false));
}
Ok(())
})
})?;
let canvas = canvas_surface(BoxDecoration::default(), surface_beneath(sheet, &style));
let svg_definitions = crate::document::svg::SvgDefinitions::collect(
html,
&style,
&crate::document::svg::Styling { sheet, resolver },
)?;
return Ok(Formatted {
root: BlockBox::anonymous(style, vec![BlockContent::Events(events)], None),
navigation,
strings,
generated: generated.finish(),
canvas,
pages: crate::document::page::PageProvider::new(
page,
images.clone(),
base.clone(),
bindings,
),
svg_definitions,
});
}
normalize_root_display(&mut style.display);
let mut traversal = Traversal {
document: html,
embedded,
root_style: style.clone(),
counters: Default::default(),
navigation,
strings: crate::document::strings::StringAssignments::new(html),
generated,
quotes: Default::default(),
canvas: BoxDecoration::default(),
canvas_body: (style.decoration.background.alpha == 0.0
&& !style.decoration.backgrounds.has_images())
.then(|| html.body_element().map(Element::id))
.flatten(),
};
traversal
.counters
.prepare(&style.counters, html, sheet, &style, resolver)?;
traversal.counters.enter(
crate::style::PageStyleTarget {
element: element.id(),
pseudo: None,
},
&style.counters,
&style.display,
style.containment().style,
)?;
let ordinal = if style.display.is_list_item() {
traversal.counters.ordinal()?
} else {
0
};
let surface = surface_beneath(sheet, &style);
let svg_definitions = crate::document::svg::SvgDefinitions::collect(
html,
&style,
&crate::document::svg::Styling { sheet, resolver },
)?;
let mut root = block(
element,
Box::new(style),
sheet,
0,
ordinal,
&mut traversal,
&mut resources,
)?;
root.trim_text_boxes([false; 2])?;
Ok(Formatted {
root,
navigation: traversal.navigation,
strings: traversal.strings,
generated: traversal.generated.finish(),
canvas: canvas_surface(traversal.canvas, surface),
pages: crate::document::page::PageProvider::new(
page,
images.clone(),
base.clone(),
bindings,
),
svg_definitions,
})
}
#[cfg(test)]
mod normalization_tests {
use super::*;
#[test]
fn grid_normalization_preserves_inner_layout_and_replaced_content() {
for (mut display, expected) in [
(Display::Grid, Display::Grid),
(Display::InlineGrid, Display::Grid),
(Display::InlineFlex, Display::Flex),
(Display::InlineTable, Display::Table),
(Display::Contents, Display::Block),
] {
let authored = display.clone();
normalize_root_display(&mut display);
assert_eq!(display, expected, "root {authored:?}");
}
for parent in [Display::Block, Display::Grid, Display::InlineGrid] {
for mut display in [Display::Grid, Display::InlineGrid] {
let authored = display.clone();
normalize_child_display(&mut display, true, &parent);
let expected = if parent.is_item_container() {
Display::Block
} else {
Display::Inline
};
assert_eq!(display, expected, "replaced {authored:?} in {parent:?}");
}
}
}
}