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};
use first_line_copies::FirstLineBox;
mod first_line_copies;
pub(crate) const MAX_FORMATTING_DEPTH: usize = 512;
pub(crate) const BOX_DEPTH: usize = 1;
pub(crate) const ATOMIC_INLINE_DEPTH: usize = 13;
pub(super) const TABLE_DEPTH: usize = 19;
pub(super) const FLEX_DEPTH: usize = 14;
pub(super) const GRID_DEPTH: usize = 16;
pub(super) const FLOAT_DEPTH: usize = 14;
pub(crate) const POSITIONED_DEPTH: usize = 11;
pub(super) const MULTICOL_DEPTH: usize = 127;
pub(super) const FILTER_DEPTH: usize = 20;
pub(super) const ORTHOGONAL_DEPTH: usize = 63;
pub(crate) const MAX_FORMATTING_WORK: usize = 100_000_000;
pub(super) const ELEMENT_WORK: usize = 64;
const DEFAULT_DENSITY: f32 = 1.0;
pub(super) const FORMATTING_NESTING_RESOURCE: &str = "formatting nesting";
const MATHML_NESTING_RESOURCE: &str = "MathML nesting";
const FORMATTING_WORK_RESOURCE: &str = "formatting work";
const TRUNCATED_CONTENT: &str = "the document content past it is left out";
const TEXT_LIMIT_RESOURCE: &str = "paragraph text bytes";
const LIMITED_TEXT: &str =
"text past it is left out, and text transforms expanding past it are not applied";
const UNEVALUATED_COUNTERS: &str = "counters past it are no longer evaluated and read as zero";
const FLATTENED_NESTING: &str = "elements nested deeper generate no boxes of their own, their contents lying in the deepest box";
const DISPLAY: &str = "display";
const GENERATED_LIST_ITEM: &str = "unsupported CSS: list items generated by pseudo-elements";
pub(super) fn background_only<I: Clone>(
decoration: &crate::paint::BoxDecoration<I>,
) -> crate::paint::BoxDecoration<I> {
crate::paint::BoxDecoration {
background: decoration.background,
backgrounds: decoration.backgrounds.clone(),
..Default::default()
}
}
fn canvas_background<I: Clone>(
decoration: &crate::paint::BoxDecoration<I>,
) -> crate::paint::BoxDecoration<I> {
let mut canvas = background_only(decoration);
let backgrounds = &mut canvas.backgrounds;
if backgrounds.clips_to_text() {
for clip in &mut std::sync::Arc::make_mut(backgrounds).clips {
if let crate::paint::BackgroundClip::Painted {
border_area: false,
text: true,
} = clip
{
*clip = crate::paint::BackgroundClip::default();
} else if let crate::paint::BackgroundClip::Painted { text, .. } = clip {
*text = false;
}
}
}
canvas
}
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)
}
}
}
#[derive(Clone)]
pub(crate) struct PageBox {
pub request: crate::style::PageRequest,
pub geometry: crate::style::PageGeometry,
pub style: Box<Style>,
pub production: crate::style::PageProduction,
pub decoration: BoxDecoration,
pub counters: crate::style::CounterProperties,
pub margins: Vec<PageMarginBox>,
pub footnote: PageFootnoteArea,
}
#[derive(Clone)]
pub(crate) struct PageFootnoteArea {
pub style: Box<Style>,
pub decoration: BoxDecoration,
}
#[derive(Clone)]
pub(crate) struct PageMarginBox {
pub margin: crate::style::PageMargin,
pub decoration: BoxDecoration,
}
pub(crate) struct Formatted {
pub root: BlockBox,
pub footnotes: Footnotes,
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 page_counters: Vec<(usize, crate::document::CounterSnapshot)>,
pub scroll_markers: crate::document::scroll_markers::ScrollMarkerGroups,
pub skipped_work: Option<usize>,
pub diagnostics: Vec<crate::document::DocumentDiagnostic>,
pub truncated: Option<usize>,
}
#[derive(Default)]
pub(crate) struct Footnotes {
pub elements: Vec<FootnoteElement>,
pub bodies: Vec<FootnoteBody>,
}
#[derive(Clone)]
pub(crate) struct FootnoteElement {
pub element: ElementId,
pub policy: crate::style::FootnotePolicy,
pub body: usize,
}
pub(crate) struct FootnoteBody {
pub block: BlockBox,
pub members: Vec<usize>,
pub inline: bool,
}
struct InlineFootnotes {
style: Box<Style>,
children: Vec<BlockContent>,
inline: InlineCollector,
members: Vec<usize>,
}
impl InlineFootnotes {
fn finish(mut self) -> Result<FootnoteBody, DocumentError> {
push_inline(&mut self.children, self.inline.finish(&self.style)?);
mark_last_formatted_line(&mut self.children);
Ok(FootnoteBody {
block: BlockBox::anonymous(*self.style, self.children, None),
members: self.members,
inline: true,
})
}
}
fn push_inline(children: &mut Vec<BlockContent>, finished: Result<Paragraph, Vec<BlockContent>>) {
match finished {
Ok(mut paragraph) => {
let first = !children
.iter()
.any(|child| matches!(child, BlockContent::Block(_) | BlockContent::Inline(_)));
paragraph.set_formatted_lines(first, false);
children.push(BlockContent::Inline(paragraph));
}
Err(stray) => children.extend(stray),
}
}
fn mark_last_formatted_line(children: &mut [BlockContent]) {
if let Some(BlockContent::Inline(paragraph)) = children
.iter_mut()
.rfind(|child| matches!(child, BlockContent::Block(_) | BlockContent::Inline(_)))
{
paragraph.set_formatted_lines(paragraph.first_formatted_line(), true);
}
}
pub(crate) struct BlockBox {
style: Box<Style>,
flow: Option<Box<BlockBox>>,
math: Option<Box<crate::document::mathml::Element>>,
math_content: Option<Box<BlockBox>>,
layout_flow: crate::style::logical::Flow,
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,
column_text_trim: [bool; 2],
first_line_box: Option<std::rc::Rc<FirstLineBox>>,
own_copy: Option<first_line_copies::OwnCopy>,
annotation_source: Option<Box<Paragraph>>,
}
#[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(crate) fn math(&self) -> Option<&crate::document::mathml::Element> {
self.math.as_deref()
}
pub(crate) fn math_content(&self) -> Option<&BlockBox> {
self.math_content.as_deref()
}
pub(crate) fn math_attributes(&self) -> Option<&crate::document::mathml::Attributes> {
self.math().map(|math| &math.attributes)
}
pub(super) fn set_math(&mut self, math: crate::document::mathml::Element) {
if matches!(self.style.display, Display::BlockMath | Display::InlineMath) {
let token = matches!(
math.name.as_ref(),
"mi" | "mn" | "mo" | "mtext" | "ms" | "annotation"
);
let children = std::mem::take(&mut self.children)
.into_iter()
.map(|child| {
if !token && let BlockContent::Inline(paragraph) = child {
let style = paragraph.style().anonymous(Display::Block);
BlockContent::Block(Self::anonymous(
style,
vec![BlockContent::Inline(paragraph)],
None,
))
} else {
child
}
})
.collect();
self.math_content = Some(Box::new(Self::anonymous(
self.style.anonymous(Display::Block),
children,
None,
)));
}
self.math = Some(Box::new(math));
}
pub(crate) fn flow(&self) -> Option<&BlockBox> {
self.flow.as_deref()
}
pub(crate) fn layout_flow(&self) -> crate::style::logical::Flow {
self.layout_flow
}
pub(super) fn reflow(&mut self, parent: crate::style::logical::Flow) {
let mut copies = Vec::new();
self.reflow_in(parent, [parent; 2], &mut copies);
while let Some((copy, parent, containers)) = copies.pop() {
copy.resolve(|block| block.reflow_in(parent, containers, &mut copies));
}
}
fn reflow_in(
&mut self,
parent: crate::style::logical::Flow,
containers: [crate::style::logical::Flow; 2],
copies: &mut Vec<(
std::rc::Rc<FirstLineBox>,
crate::style::logical::Flow,
[crate::style::logical::Flow; 2],
)>,
) {
use crate::style::logical::{self, Flow};
enum Entry<'a> {
Block(&'a mut BlockBox, Flow, [Flow; 2]),
Paragraph(&'a mut Paragraph, Flow, [Flow; 2]),
}
let mut pending = vec![Entry::Block(self, parent, containers)];
while let Some(entry) = pending.pop() {
let (block, parent, mut containers) = match entry {
Entry::Block(block, parent, containers) => {
if let Some(copy) = block.first_line_box.as_ref().or(block.moved_copy()) {
copies.push((copy.clone(), parent, containers));
}
if block.stands_in() {
continue;
}
(block, parent, containers)
}
Entry::Paragraph(paragraph, flow, containers) => {
pending.extend(
paragraph
.reflow()
.into_iter()
.map(|block| Entry::Block(block, flow, containers)),
);
continue;
}
};
let parent = match block.style.position {
crate::style::Position::Absolute => containers[0],
crate::style::Position::Fixed => containers[1],
_ => parent,
};
let computed = Flow::of(&block.style);
if (block.style.display.is_table_internal()
&& block.style.display != Display::TableCell)
|| matches!(
block.style.display,
Display::RubyBaseContainer | Display::RubyTextContainer
)
{
block.style.principal_flow = Some(parent);
}
let own = Flow::used(&block.style);
if block.style.contains_absolute() {
containers[0] = own;
}
if block.style.contains_fixed() {
containers[1] = own;
}
block.layout_flow = parent;
block.style.anchor.physical_areas(own, parent);
if own.writing_mode != parent.writing_mode && block.image.is_none() {
let mut style = block.style.anonymous(block.style.display.clone());
style.flex = block.style.flex.clone();
style.grid = block.style.grid.clone();
style.table = block.style.table.clone();
style.multicol = block.style.multicol.clone();
style.clamp = block.style.clamp.clone();
style.text_box = block.style.text_box;
style.margin_trim = block.style.margin_trim;
let mut inner = Self::anonymous(style, Vec::new(), None);
if block.style.display.is_table()
&& block.style.table.collapse == crate::style::BorderCollapse::Collapse
{
inner.style.decoration.borders = block.style.decoration.borders;
inner.decoration = block.decoration.clone();
}
inner.children = std::mem::take(&mut block.children);
inner.marker = block.marker.take();
block.flow = Some(Box::new(inner));
block.style.display = if matches!(
block.style.display,
Display::TableCell | Display::TableCaption
) {
block.style.display.clone()
} else if block.style.display.is_inline_level() {
Display::InlineBlock
} else {
Display::FlowRoot
};
}
if let Some(inner) = &mut block.flow {
inner.math = block.math.take();
inner.math_content = block.math_content.take();
}
if parent.writing_mode.vertical() {
let mut physical = (*block.style).clone();
physical.writing_mode = parent.writing_mode;
physical.rtl = parent.rtl;
block.decoration =
logical::decoration(&block.decoration, parent, parent.horizontal());
*block.style = logical::reflowed(&physical, parent.horizontal());
}
block.style.writing_mode = computed.writing_mode;
block.style.rtl = computed.rtl;
block.style.layout_writing_mode = parent.writing_mode;
if let Some(inner) = &mut block.flow {
pending.push(Entry::Block(inner, own, containers));
}
if let Some(content) = &mut block.math_content {
pending.push(Entry::Block(content, own, containers));
}
for child in &mut block.children {
match child {
BlockContent::Block(child) | BlockContent::Positioned(child) => {
pending.push(Entry::Block(child, own, containers));
}
BlockContent::Inline(paragraph) => {
pending.push(Entry::Paragraph(paragraph, own, containers));
}
BlockContent::Events(_) => {}
}
}
if let Some(marker) = &mut block.marker {
pending.push(Entry::Paragraph(marker, own, containers));
}
}
}
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
}
fn join_table_part(&mut self, part: BlockBox, page_scope: Option<std::sync::Arc<str>>) {
let mut parts = Vec::new();
for child in std::mem::take(&mut self.children) {
match child {
BlockContent::Block(row)
if row.anonymous && row.style.display == Display::TableRow =>
{
parts.extend(row.children);
}
child => parts.push(child),
}
}
parts.push(BlockContent::Block(part));
*self = Self::anonymous((*self.style).clone(), parts, page_scope);
}
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 {
layout_flow: crate::style::logical::Flow::of(&style),
style: Box::new(style),
flow: None,
math: None,
math_content: None,
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,
column_text_trim: [false; 2],
first_line_box: None,
own_copy: None,
annotation_source: None,
}
}
pub(crate) fn column_text_trim(&self) -> [bool; 2] {
self.column_text_trim
}
pub(crate) fn first_line_box(&self) -> Option<&BlockBox> {
self.first_line_box.as_deref().and_then(FirstLineBox::get)
}
pub(super) fn set_first_line_box(&mut self, block: BlockBox) {
self.first_line_box = Some(FirstLineBox::staged(block));
}
fn moved_copy(&self) -> Option<&std::rc::Rc<FirstLineBox>> {
match &self.own_copy {
Some(first_line_copies::OwnCopy::Moved(copy)) => Some(copy),
_ => None,
}
}
pub(crate) fn standing_for(&self) -> &BlockBox {
self.moved_copy()
.and_then(|copy| copy.get())
.unwrap_or(self)
}
pub(crate) fn stands_in(&self) -> bool {
self.moved_copy().is_some()
}
pub(super) fn annotation_contents_mut(&mut self) -> Option<&mut Paragraph> {
match self.children.first_mut() {
Some(BlockContent::Inline(contents)) => Some(contents),
_ => None,
}
}
pub(super) fn keep_annotation_source(&mut self, contents: Paragraph) {
self.annotation_source = Some(Box::new(contents));
}
pub(super) fn take_annotation_source(&mut self) -> Option<Paragraph> {
self.annotation_source.take().map(|contents| *contents)
}
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 subtree_events(&self) -> (Vec<&crate::document::SemanticEvent>, usize) {
let mut events = self.semantic_event().into_iter().collect();
let visited = 1 + content_events(&self.children, &mut events);
events.sort_by_key(|event| event.order.start);
(events, visited)
}
pub(crate) fn image(&self) -> Option<&std::sync::Arc<crate::images::Image>> {
self.image.as_ref()
}
pub(crate) fn is_unadorned_image_fallback(&self) -> bool {
self.empty_image_fallback
&& self.style.width == crate::style::Size::Auto
&& self.style.height == crate::style::Size::Auto
&& !self.style.has_inline_edges([false; 2])
&& self.style.margin.iter().all(crate::style::Size::is_zero)
&& !self.decoration.is_visible()
}
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(crate) fn omit(&mut self, target: *const BlockBox, following: bool) -> bool {
if std::ptr::eq(self, target) {
self.omit_content();
return true;
}
for index in 0..self.children.len() {
let found = match &mut self.children[index] {
BlockContent::Block(block) | BlockContent::Positioned(block) => {
if std::ptr::eq(block, target) {
Some(true)
} else {
block.omit(target, following).then_some(false)
}
}
BlockContent::Inline(paragraph) => paragraph
.anchors()
.iter()
.chain(paragraph.inline_blocks())
.any(|anchor| anchor.block().holds(target))
.then_some(true),
BlockContent::Events(_) => None,
};
if let Some(removed) = found {
if following {
self.children.truncate(index + usize::from(!removed));
} else if removed {
self.children.remove(index);
}
return true;
}
}
if self.first_line_box().is_some_and(|copy| copy.holds(target)) {
self.first_line_box = None;
return true;
}
[&mut self.math_content, &mut self.flow]
.into_iter()
.flatten()
.any(|block| block.omit(target, following))
}
pub(crate) fn omit_content(&mut self) {
self.children.clear();
}
fn holds(&self, target: *const BlockBox) -> bool {
std::ptr::eq(self, target)
|| self.children.iter().any(|child| match child {
BlockContent::Block(block) | BlockContent::Positioned(block) => block.holds(target),
BlockContent::Inline(paragraph) => paragraph
.anchors()
.iter()
.chain(paragraph.inline_blocks())
.any(|anchor| anchor.block().holds(target)),
BlockContent::Events(_) => false,
})
|| [
self.first_line_box(),
self.math_content.as_deref(),
self.flow.as_deref(),
]
.into_iter()
.flatten()
.any(|block| block.holds(target))
}
pub(super) fn trim_text_boxes(&mut self, requested: [bool; 2]) {
let mut pending = vec![(self, requested)];
while let Some((block, requested)) = pending.pop() {
let requested = if block.initial_letter.is_some_and(|letter| !letter.atomic) {
[true; 2]
} else {
requested
};
let own = block.style.text_box.trim;
let display = &block.style.display;
let requested = if display.is_item_container() || display.is_table() {
[false; 2]
} else if block.style.multicol.is_multicol() {
block.column_text_trim = [0, 1].map(|side| own[side] || requested[side]);
[false; 2]
} else {
[0, 1].map(|side| own[side] || requested[side])
};
let in_flow: Vec<usize> = block
.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()];
if let Some(content) = &mut block.math_content {
pending.push((content.as_mut(), [false; 2]));
}
for (index, child) in block.children.iter_mut().enumerate().rev() {
let inherited = [
requested[0] && first == Some(index),
requested[1] && last == Some(index),
];
match child {
BlockContent::Inline(paragraph) => {
paragraph.set_text_box_trim(inherited);
let start = pending.len();
pending.extend(
paragraph
.anchored_blocks_mut()
.map(|block| (block, [false; 2])),
);
pending[start..].reverse();
}
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
};
let inherited = [inherited[0] && open(TOP), inherited[1] && open(BOTTOM)];
pending.push((block, inherited));
}
BlockContent::Positioned(block) => pending.push((block, [false; 2])),
BlockContent::Events(_) => {}
}
}
}
}
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
}
}
fn content_events<'a>(
children: &'a [BlockContent],
events: &mut Vec<&'a crate::document::SemanticEvent>,
) -> usize {
let mut pending = vec![children];
let mut visited = 0;
while let Some(children) = pending.pop() {
for child in children {
let blocks: Vec<&BlockBox> = match child {
BlockContent::Events(values) => {
events.extend(values);
Vec::new()
}
BlockContent::Block(child) | BlockContent::Positioned(child) => vec![child],
BlockContent::Inline(paragraph) => {
events.extend(paragraph.semantic_events().iter().map(|event| &event.event));
paragraph
.anchors()
.iter()
.chain(paragraph.inline_blocks())
.map(crate::document::Anchor::block)
.collect()
}
};
for block in blocks {
visited += 1;
events.extend(block.semantic_event());
pending.push(&block.children);
}
}
}
visited
}
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>,
footnotes: Footnotes,
inline_footnotes: Option<Box<InlineFootnotes>>,
page_counters: Vec<(usize, crate::document::CounterSnapshot)>,
running: Vec<crate::style::PageStyleTarget>,
pages: &'a crate::document::page::PageProvider,
scroll_markers: std::collections::HashMap<ElementId, Vec<GeneratedBox>>,
marker_prepass: bool,
prepassed_markers: std::collections::HashMap<ElementId, Vec<GeneratedBox>>,
marker_scroller: Option<MarkerScroller>,
marker_groups: crate::document::scroll_markers::ScrollMarkerGroups,
work: crate::layout::work::Budget,
kind: TraversalKind,
first_lines: std::rc::Rc<std::cell::RefCell<first_line_copies::FirstLineCopies>>,
requests: Vec<first_line_copies::CopyRequest<'a>>,
flattened: std::collections::BTreeSet<(&'static str, usize)>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum TraversalKind {
Document,
Copy,
FirstLineCopy,
}
#[derive(Clone)]
struct MarkerScroller {
element: ElementId,
group: Option<Display>,
}
impl Traversal<'_> {
fn inline_footnotes_style(
&self,
element: ElementId,
sheet: &Stylesheet,
resources: &mut ImageResources<'_>,
) -> Result<Style, DocumentError> {
Ok(match self.generated.inline_footnote_page(element) {
Some(request) => self
.pages
.resolve_with(sheet, &self.root_style, request.clone(), resources)?
.footnote
.style
.anonymous(Display::Block),
None => self.pages.first().footnote.style.anonymous(Display::Block),
})
}
fn canvas_source(&self, index: usize, element: Element<'_>) -> bool {
(index == 0 && self.kind == TraversalKind::Document)
|| self.canvas_body == Some(element.id())
}
fn finish_inline_footnotes(&mut self) -> Result<(), DocumentError> {
if let Some(open) = self.inline_footnotes.take() {
for &member in &open.members {
self.footnotes.elements[member].body = self.footnotes.bodies.len();
}
self.footnotes.bodies.push(open.finish()?);
}
Ok(())
}
fn add_footnote(&mut self, element: ElementId, style: &Style) -> usize {
self.footnotes.elements.push(FootnoteElement {
element,
policy: style.footnote_policy,
body: self.footnotes.bodies.len(),
});
self.footnotes.elements.len() - 1
}
fn bind<'c>(
&self,
content: &'c crate::style::GeneratedContent,
context: crate::style::PageStyleTarget,
running: bool,
) -> Result<std::borrow::Cow<'c, crate::style::GeneratedContent>, DocumentError> {
let owner = if running {
Some(context)
} else {
self.running.last().copied()
};
Ok(match owner {
Some(owner) => self.generated.bind_running(content, context, owner)?,
None => self.generated.bind(content, context)?,
})
}
fn running_copy(
&self,
owner: crate::style::PageStyleTarget,
numbers: crate::document::generated::PageNumbers,
) -> Self {
Self {
document: self.document,
embedded: self.embedded,
root_style: self.root_style.clone(),
counters: self.counters.detached(),
navigation: self.navigation.detached(),
strings: crate::document::strings::StringAssignments::new(self.document),
generated: self.generated.running_copy(numbers),
quotes: self.quotes,
canvas: BoxDecoration::default(),
canvas_body: None,
footnotes: Footnotes::default(),
inline_footnotes: None,
page_counters: Vec::new(),
running: vec![owner],
pages: self.pages,
scroll_markers: std::collections::HashMap::new(),
marker_prepass: self.marker_prepass,
prepassed_markers: std::collections::HashMap::new(),
marker_scroller: None,
marker_groups: crate::document::scroll_markers::ScrollMarkerGroups::default(),
work: self.work.clone(),
kind: TraversalKind::Copy,
first_lines: std::rc::Rc::new(std::cell::RefCell::new(
first_line_copies::FirstLineCopies::new(self.first_lines.borrow().enabled()),
)),
requests: Vec::new(),
flattened: std::collections::BTreeSet::new(),
}
}
fn subtree_copy(&self, kind: TraversalKind) -> Self {
Self {
document: self.document,
embedded: self.embedded,
root_style: self.root_style.clone(),
counters: self.counters.detached(),
navigation: self.navigation.detached(),
strings: self.strings.detached(),
generated: self.generated.detached(),
quotes: self.quotes,
canvas: BoxDecoration::default(),
canvas_body: None,
footnotes: Footnotes {
elements: self.footnotes.elements.clone(),
bodies: Vec::new(),
},
inline_footnotes: None,
page_counters: Vec::new(),
running: self.running.clone(),
pages: self.pages,
scroll_markers: std::collections::HashMap::new(),
marker_prepass: self.marker_prepass,
prepassed_markers: std::collections::HashMap::new(),
marker_scroller: None,
marker_groups: crate::document::scroll_markers::ScrollMarkerGroups::default(),
work: self.work.clone(),
kind,
first_lines: self.first_lines.clone(),
requests: Vec::new(),
flattened: std::collections::BTreeSet::new(),
}
}
}
fn marker_scroller(frames: &[Frame<'_>], traversal: &Traversal<'_>) -> Option<MarkerScroller> {
frames
.iter()
.rev()
.find(|frame| frame.scroll_container)
.map(|frame| MarkerScroller {
element: frame.element.id(),
group: frame
.marker_group
.as_ref()
.map(|group| group.display.clone()),
})
.or_else(|| traversal.marker_scroller.clone())
}
fn record_scroll_marker_box(
frames: &[Frame<'_>],
(element, style): (Element<'_>, &Style),
scroll_container: bool,
traversal: &mut Traversal<'_>,
) {
let scroller = marker_scroller(frames, traversal);
let groups = &mut traversal.marker_groups;
if let Some(scroller) = scroller {
groups.element(element.id(), scroller.element);
if scroll_container {
groups.scroller(element.id(), Some(scroller.element), style);
}
}
if traversal.navigation.is_scroll_target(element.id()) {
groups.target(element.id(), style);
}
if let Some(target) = traversal.navigation.scroll_target(element.id())
&& let Some(container) = frames
.iter()
.rev()
.find(|frame| frame.style.scroll_markers.target_group)
{
groups.anchor(container.element.id(), element.id(), target);
}
}
#[inline(never)]
fn marker_group_style(
element: Element<'_>,
style: &Style,
sheet: &Stylesheet,
resolver: &dyn crate::resources::ResourceResolver,
) -> Result<Option<Box<Style>>, DocumentError> {
if style.scroll_markers.group == crate::style::ScrollMarkerGroup::None {
return Ok(None);
}
let group = sheet
.element_backed_with_resolver(element, style, PseudoElement::ScrollMarkerGroup, resolver)?
.used();
Ok((group.display != Display::None).then(|| Box::new(group)))
}
#[inline(never)]
fn scroll_marker<'a>(
frames: &mut [Frame<'_>],
block_index: usize,
(element, style): (Element<'_>, &Style),
sheet: &'a Stylesheet,
traversal: &mut Traversal<'a>,
resources: &mut ImageResources<'a>,
) -> Result<(), DocumentError> {
let Some((scroller, group)) = marker_scroller(frames, traversal)
.and_then(|scroller| Some((scroller.element, scroller.group?)))
else {
return Ok(());
};
let Some((marker, content)) = sheet.pseudo_with_resolver(
element,
style,
PseudoElement::ScrollMarker,
resources.resolver,
)?
else {
return Ok(());
};
traversal
.marker_groups
.scroll_marker(scroller, element.id());
traversal.marker_groups.target(element.id(), style);
let navigation = traversal.navigation.scroll_marker(element.id());
let detached = traversal.counters.detached();
let counters = std::mem::replace(&mut traversal.counters, detached);
let quotes = traversal.quotes;
let (mut builder, _) = active_builder(frames, block_index, sheet, traversal, resources);
let generated = builder.generated_box(
(element, style, &group),
GeneratedPseudoElement::ScrollMarker,
marker,
&content,
navigation,
);
traversal.counters = counters;
traversal.quotes = quotes;
if let Some(generated) = generated? {
traversal
.scroll_markers
.entry(scroller)
.or_default()
.push(generated);
}
Ok(())
}
fn root_marker_group(
frames: &[Frame<'_>],
index: usize,
traversal: &Traversal<'_>,
side: crate::style::ScrollMarkerGroup,
) -> Option<Style> {
let root = &frames[index];
(index == 0
&& !traversal.marker_prepass
&& root.element.id() == traversal.document.root_element().id()
&& root.style.scroll_markers.group == side)
.then(|| root.marker_group.as_deref().cloned())
.flatten()
}
#[inline(never)]
fn collect_scroll_markers<'a>(
frame: Frame<'a>,
sheet: &'a Stylesheet,
traversal: &mut Traversal<'a>,
resources: &mut ImageResources<'a>,
) -> Result<Vec<GeneratedBox>, DocumentError> {
let element = frame.element.id();
if let Some(markers) = traversal.prepassed_markers.remove(&element) {
return Ok(markers);
}
let mut copy = traversal.subtree_copy(TraversalKind::Copy);
copy.marker_prepass = true;
block(frame, sheet, &mut copy, resources)?;
traversal.prepassed_markers.extend(copy.prepassed_markers);
Ok(copy.scroll_markers.remove(&element).unwrap_or_default())
}
fn running_copies<'a>(
(frame, scroller): (&Frame<'a>, Option<MarkerScroller>),
sheet: &'a Stylesheet,
traversal: &Traversal<'a>,
resources: &mut ImageResources<'a>,
) -> Result<Vec<(crate::document::generated::PageNumbers, BlockBox)>, DocumentError> {
let owner = crate::style::PageStyleTarget {
element: frame.element.id(),
pseudo: None,
};
if traversal.generated.formats_copy() || traversal.marker_prepass {
return Ok(Vec::new());
}
traversal
.generated
.running_pages(owner)
.iter()
.map(|&numbers| {
let mut copy = traversal.running_copy(owner, numbers);
copy.marker_scroller.clone_from(&scroller);
Ok((
numbers,
block(
frame.copy_root(frame.style.clone()),
sheet,
&mut copy,
resources,
)?,
))
})
.collect()
}
struct BlockBuilder<'a, 's, 'c> {
sheet: &'a Stylesheet,
element: ElementId,
style: &'s Style,
sized: &'s mut bool,
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<Box<OpenLetter>>,
ruby: &'s mut crate::document::ruby::RubyStack,
traversal: &'c mut Traversal<'a>,
resources: &'c mut ImageResources<'a>,
}
struct GeneratedBox {
style: Style,
decoration: BoxDecoration,
contents: GeneratedContents,
replacement: Option<std::sync::Arc<crate::images::Image>>,
event: Option<crate::document::SemanticEvent>,
navigation: BoxNavigation,
element_page_scope: Option<std::sync::Arc<str>>,
run_in: bool,
}
enum GeneratedContents {
Output {
output: crate::style::GeneratedOutput,
images: Vec<crate::document::inline::GeneratedImage>,
},
Markers(Vec<GeneratedBox>),
}
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,
}
const SAME_DOCUMENT: char = '#';
const LINKING_PROPERTY: &str = "filter";
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,
pub elements: &'a crate::document::element_images::ElementImages,
}
impl ImageResources<'_> {
fn load(
&mut self,
reference: &crate::paint::ImageReference<'_>,
style: &Style,
) -> Option<std::sync::Arc<crate::images::Image>> {
let request = match reference {
crate::paint::ImageReference::Url(request) => request,
crate::paint::ImageReference::Element(id) => return self.element(id, style),
};
let image = self.cache.load_optional(
request.url,
self.base,
self.resolver,
style.element_font_namespace(),
)?;
self.view(image, request, style)
}
pub(crate) fn load_decoded(
&mut self,
reference: &crate::paint::ImageReference<'_>,
style: &Style,
) -> Option<std::sync::Arc<crate::images::Image>> {
let request = match reference {
crate::paint::ImageReference::Url(request) => request,
crate::paint::ImageReference::Element(id) => return self.element(id, style),
};
let image = self.cache.load_decoded(
request.url,
self.base,
self.resolver,
style.element_font_namespace(),
)?;
self.view(image, request, style)
}
fn view(
&mut self,
image: std::sync::Arc<crate::images::Image>,
request: &crate::paint::ImageRequest<'_>,
style: &Style,
) -> Option<std::sync::Arc<crate::images::Image>> {
self.cache.view(image, request, self.base, style)
}
fn element(&mut self, id: &str, style: &Style) -> Option<std::sync::Arc<crate::images::Image>> {
use crate::document::element_images::Resolved;
let owner = style.origin.node().map(|node| node.element);
let namespace = crate::fonts::FontNamespace::ROOT;
match self.elements.resolve(id, owner) {
Resolved::Invalid => None,
Resolved::Rendering(element, size) => Some(std::sync::Arc::new(
crate::images::Image::Element(crate::images::ElementImage { element, size }),
)),
Resolved::Image(url, density) => self
.cache
.load_optional(url, self.base, self.resolver, namespace)
.map(|image| crate::images::content_image(image, &Style::default(), density)),
Resolved::Poster(poster) => Some(
poster
.and_then(|poster| {
self.cache
.load_optional(poster, self.base, self.resolver, namespace)
})
.map_or_else(
|| std::sync::Arc::new(crate::images::Image::Transparent),
|image| crate::images::content_image(image, &Style::default(), None),
),
),
Resolved::Svg(xml, styling) => {
match self.cache.inline_svg_in_namespace(
xml,
styling,
self.base,
self.resolver,
namespace,
) {
Ok(image) => Some(image),
Err(error) => {
let reference = format!("element(#{id})");
self.cache.record_failure(self.base, &reference, error);
None
}
}
}
}
}
pub(crate) fn content_image(
&mut self,
image: &crate::paint::BackgroundImage,
style: &Style,
) -> Option<std::sync::Arc<crate::images::Image>> {
let namespace = style.element_font_namespace();
let resolution = match image {
crate::paint::BackgroundImage::Url { resolution, .. } => Some(*resolution),
_ => None,
};
let mut loaded = image.with_image_type();
let Ok(()) = loaded.load(style.image_rendering(), &mut |reference| {
let request = match reference {
crate::paint::ImageReference::Url(request) => request,
crate::paint::ImageReference::Element(id) => {
return Ok::<_, std::convert::Infallible>(self.element(id, style));
}
};
Ok(self
.cache
.load_optional(request.url, self.base, self.resolver, namespace)
.and_then(|image| match resolution {
Some(resolution) => self
.cache
.content_view(image, request, self.base, style, resolution),
None => self.view(image, request, style),
}))
});
match loaded {
crate::graphics::BackgroundImage::Image { image, .. } => Some(image),
generated => generated
.is_displayable()
.then(|| generated_image(generated, style)),
}
}
pub(crate) fn replacement_image(
&mut self,
image: &crate::paint::BackgroundImage,
style: &Style,
) -> std::sync::Arc<crate::images::Image> {
self.content_image(image, style).unwrap_or_else(|| {
std::sync::Arc::new(crate::images::Image::Generated(std::sync::Arc::new(
crate::graphics::BackgroundImage::Invalid,
)))
})
}
pub(crate) fn generated_images(
&mut self,
output: &crate::style::GeneratedOutput,
style: &Style,
) -> Vec<crate::document::inline::GeneratedImage> {
output
.images()
.iter()
.filter_map(|(offset, image)| {
Some(crate::document::inline::GeneratedImage {
offset: *offset,
image: self.content_image(image, style)?,
})
})
.collect()
}
pub(crate) fn shape_outside(&mut self, style: &Style) -> crate::graphics::ShapeOutside {
if style.floating().is_none() {
return crate::graphics::ShapeOutside::None;
}
let Ok(shape) = style
.shape_outside
.load_image(style.image_rendering(), &mut |request| {
Ok::<_, std::convert::Infallible>(self.load_decoded(request, style))
});
shape
}
pub(crate) fn backgrounds(&mut self, style: &Style) -> BoxDecoration {
self.link_documents(style);
let Ok(decoration) = style
.decoration
.load_images(style.image_rendering(), |request| {
Ok::<_, std::convert::Infallible>(self.load(request, style))
});
decoration
}
pub(crate) fn masks(&mut self, style: &Style) -> std::sync::Arc<crate::graphics::LoadedMasks> {
self.link_documents(style);
let masks = crate::paint::BoxDecoration {
masks: style.decoration.masks.clone(),
..crate::paint::BoxDecoration::default()
};
let Ok(loaded) = masks.load_images(style.image_rendering(), |request| {
Ok::<_, std::convert::Infallible>(self.load(request, style))
});
loaded.masks
}
fn link_documents(&mut self, style: &Style) {
let masks = &style.decoration.masks;
let references = style
.filter
.iter()
.chain(style.backdrop_filter.iter())
.filter_map(|function| match function {
crate::paint::FilterFunction::Url(reference) => Some(&**reference),
_ => None,
})
.chain(masks.sources.iter().flatten().map(|reference| &**reference))
.chain(masks.clip_reference.as_deref());
for reference in references {
if reference.starts_with(SAME_DOCUMENT) {
continue;
}
let failures = std::cell::RefCell::new(Vec::new());
let load = |url: &str| {
self.cache
.linked_document(url, self.base, self.resolver)
.unwrap_or_else(|error| {
failures.borrow_mut().push((url.to_owned(), error));
None
})
};
crate::svg::reference_tree(
"",
crate::svg::DocumentStyling::default(),
LINKING_PROPERTY,
reference,
None,
&load,
);
for (url, error) in failures.into_inner() {
self.cache.record_failure(self.base, &url, error);
}
}
}
}
fn generated_image(
image: crate::graphics::BackgroundImage,
style: &Style,
) -> std::sync::Arc<crate::images::Image> {
crate::images::content_image(
std::sync::Arc::new(crate::images::Image::Generated(std::sync::Arc::new(image))),
style,
None,
)
}
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()),
}
}
const BLOCK_AXIS_SIDES: [usize; 2] = [0, 2];
fn block_axis_edges(style: &Style, basis: f32) -> f32 {
BLOCK_AXIS_SIDES
.into_iter()
.map(|side| {
style.padding[side].resolve(basis) + style.decoration.borders[side].used_width()
})
.sum()
}
fn letter_basis(
sheet: &Stylesheet,
(element, block): (ElementId, &Style),
style: &Style,
) -> Option<f32> {
if BLOCK_AXIS_SIDES.iter().all(|&side| {
matches!(
style.padding[side],
crate::style::LengthPercentage::Length(_)
)
}) {
return None;
}
Some(sheet.query_sizes().size(element).map_or(0.0, |size| {
size[usize::from(block.used_writing_mode().vertical())] * block.effective_zoom
}))
}
fn letter_atomic(
sheet: &Stylesheet,
resolver: &dyn crate::resources::ResourceResolver,
(element, block): (ElementId, &Style),
letter: &mut BlockBox,
) -> Result<bool, DocumentError> {
let context = crate::text::TextContext::new(&sheet.fonts, resolver);
let style = &mut letter.style;
let initial = style
.initial_letter
.expect("an initial letter has a size and sink");
let surrounding =
crate::text::LetterSurrounding::of(&context, block, style.initial_letter_align.alignment)
.map_err(letter_text_error)?;
let mut sized = false;
if *style.height.basis() == 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 => {
let basis = letter_basis(sheet, (element, block), style);
sized = basis.is_some();
span - block_axis_edges(style, basis.unwrap_or_default())
}
};
style.height = style.height.with_automatic(crate::style::Size::Value(
crate::style::LengthPercentage::Length(height.max(0.0)),
));
}
letter.initial_letter = Some(InitialLetterBox {
surrounding,
atomic: true,
});
Ok(sized)
}
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(());
}
let overridden = self
.ruby
.annotation_mode()
.filter(|mode| self.inline.open_style().is_none() && *mode != style.used_writing_mode())
.map(|mode| {
let mut style = style.clone();
style.writing_mode = mode;
style
});
let style = overridden.as_ref().unwrap_or(style);
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);
Ok(())
}
fn line_break(&mut self, style: &Style) {
if self.ruby.in_annotation() {
let mut collapsing = style.clone();
collapsing.white_space.collapse = crate::style::WhiteSpaceCollapse::Collapse;
self.inline.append(SEGMENT_BREAK, &collapsing);
} else {
self.inline.line_break(style);
}
}
fn append_generated(
&mut self,
output: &crate::style::GeneratedOutput,
images: &[crate::document::inline::GeneratedImage],
style: &Style,
) -> Result<(), DocumentError> {
if !output.text().is_empty() || !images.is_empty() {
self.ruby.content(self.inline)?;
}
let leader = output
.leaders()
.first()
.map(|range| range.start)
.into_iter()
.chain(images.first().map(|image| image.offset))
.min()
.unwrap_or(output.text().len());
let start = self.first_letter(&output.text()[..leader], style)?;
self.inline
.append_generated_from(output, images, start, style);
Ok(())
}
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,
)?
.used();
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(Box::new(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.display.is_table_part() {
self.table_part(block, parent);
return Ok(());
}
if block.style.initial_letter.is_none() || !self.initial_letter_allowed() {
self.inline.atomic(block, parent);
return Ok(());
}
*self.sized |= letter_atomic(
self.sheet,
self.resources.resolver,
(self.element, self.style),
&mut block,
)?;
self.inline.initial_letter(block, parent, false);
Ok(())
}
fn letter_basis(&mut self, style: &Style) -> f32 {
let basis = letter_basis(self.sheet, (self.element, self.style), style);
*self.sized |= basis.is_some();
basis.unwrap_or_default()
}
fn table_part(&mut self, part: BlockBox, parent: &Style) {
let page_scope = self.element_page_scope.clone();
if let Some(table) = self
.inline
.trailing_atomic()
.filter(|table| table.anonymous && table.style.display == Display::InlineTable)
{
table.join_table_part(part, page_scope);
self.inline.drop_pending_space();
return;
}
self.inline.atomic(
BlockBox::anonymous(
parent.anonymous(Display::InlineTable),
vec![BlockContent::Block(part)],
page_scope,
),
parent,
);
}
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();
if *style.width.basis() == crate::style::Size::Auto {
style.align = crate::style::TextAlign::Start;
style.align_last = None;
}
match contents.finish(&style)? {
Ok(paragraph) => {
let block = self.inline_letter_box(style, decoration, navigation, paragraph)?;
self.inline.initial_letter(block, &parent, marker);
Ok(())
}
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 split_letter(&mut self, letter: OpenLetter) -> Result<(), DocumentError> {
let open = self.inline.close_open();
let mut style = letter.style.clone();
style.initial_letter = None;
let (decoration, navigation) = (letter.decoration.clone(), letter.navigation);
self.finish_letter(letter, false)?;
self.inline.continue_box(&style, decoration, navigation);
self.inline.reopen(open);
Ok(())
}
fn place_inside_marker(&mut self, marker: Paragraph) -> Result<(), DocumentError> {
let style = &marker.style().clone();
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);
}
let (text, atomics) = marker.into_text_and_atomics();
let mut from = 0;
for (offset, atomic) in atomics {
self.inline.append(&text[from..offset], style);
self.inline.atomic(atomic, style);
from = offset + crate::document::OBJECT_REPLACEMENT_CHARACTER.len_utf8();
}
self.inline.append(&text[from..], 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, self.letter_basis(&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) {
self.inline.append(text, parent);
return Ok(());
}
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,
)?
.used(),
);
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: &mut 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 let Some(letter) = self.letter.take() {
self.split_letter(*letter)?;
}
self.ruby.finish(self.inline)?;
let collected = self.inline.split();
let origins = self.first_line.origins.clone();
let origins = origins.as_deref();
let finished = self.finish_inline(collected, self.style, origins)?;
if finished.is_ok() {
*self.first_line = FirstLine::default();
}
push_inline(self.children, finished);
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) {
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);
}
}
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 running(&mut self, element: Element<'_>, block: BlockBox) {
for event in block.subtree_events().0 {
self.inline.semantic_event(event.clone());
}
self.traversal.strings.attach_running(element.id(), block);
}
fn footnote(&mut self, element: Element<'_>, block: BlockBox) -> Result<(), DocumentError> {
let index = self.traversal.add_footnote(element.id(), block.style());
self.footnote_call(element, block.style(), block.subtree_events().0, index)?;
self.traversal.footnotes.bodies.push(FootnoteBody {
block,
members: vec![index],
inline: false,
});
Ok(())
}
fn footnote_call(
&mut self,
element: Element<'_>,
style: &Style,
events: Vec<&crate::document::SemanticEvent>,
index: usize,
) -> Result<(), DocumentError> {
for event in events {
let mut event = event.clone();
if event.context.element == element.id() && event.context.pseudo.is_none() {
event.footnote = Some(index);
}
self.inline.semantic_event(event);
}
self.generated(element, style, GeneratedPseudoElement::FootnoteCall)
}
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((style, content)) = self.sheet.pseudo_with_resolver(
element,
parent,
pseudo.into(),
self.resources.resolver,
)?
else {
return Ok(());
};
self.place_generated(element, parent, pseudo, style, &content)
}
fn place_generated(
&mut self,
element: Element<'_>,
parent: &Style,
pseudo: GeneratedPseudoElement,
style: Style,
content: &crate::style::GeneratedContent,
) -> Result<(), DocumentError> {
let parent_display = self.style.display.clone();
let navigation = self.traversal.navigation.descendant();
if let Some(generated) = self.generated_box(
(element, parent, &parent_display),
pseudo,
style,
content,
navigation,
)? {
self.place_generated_box(parent, generated)?;
}
Ok(())
}
fn generated_box(
&mut self,
(element, parent, parent_display): (Element<'_>, &Style, &Display),
pseudo: GeneratedPseudoElement,
mut style: Style,
content: &crate::style::GeneratedContent,
navigation: BoxNavigation,
) -> Result<Option<GeneratedBox>, DocumentError> {
style = style.used();
let running =
style.display != Display::Contents && style.position == crate::style::Position::Running;
let element_page_scope =
crate::document::page::used_name(&parent.page, self.element_page_scope.as_ref());
let replacement = content.replacement();
normalize_child_display(&mut style.display, replacement.is_some(), parent_display);
if replacement.is_some() && style.display == Display::Contents {
return Ok(None);
}
let run_in = style.display.run_in().cloned();
if let Some(inner) = run_in.clone() {
style.display = inner;
}
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 = (!running
&& (content.named_string_requests().next().is_some() || content.has_page_counters()))
.then(|| self.traversal.strings.generated_event(element, pseudo));
let bound = self.traversal.bind(content, context, running)?;
let quotes = self.traversal.quotes;
let output = content_output(
self.sheet,
&mut self.traversal.counters,
&bound,
&style.quotes,
&mut self.traversal.quotes,
)?;
let copies = if running {
self.generated_copies(content, context, &style.quotes, quotes)?
} else {
Vec::new()
};
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);
let replacement = replacement.map(|image| self.resources.replacement_image(image, &style));
if running {
let name = style
.running
.clone()
.expect("running() names the running element");
let copies = copies
.iter()
.map(|(numbers, output)| {
Ok((
*numbers,
self.running_text_block(
output,
style.clone(),
decoration.clone(),
element_page_scope.as_ref(),
)?,
))
})
.collect::<Result<_, DocumentError>>()?;
let block = if let Some(image) = replacement {
let mut block = Self::generated_block(
style,
Vec::new(),
decoration,
element_page_scope.as_ref(),
(None, navigation),
);
block.image = Some(image);
block
} else {
self.running_text_block(&output, style, decoration, element_page_scope.as_ref())?
};
let event = self
.traversal
.strings
.record_generated_running(element, pseudo, name, block, copies);
self.inline.semantic_event(event);
return Ok(None);
}
let images = self.resources.generated_images(&output, &style);
Ok(Some(GeneratedBox {
style,
decoration,
contents: GeneratedContents::Output { output, images },
replacement,
event,
navigation,
element_page_scope,
run_in: run_in.is_some(),
}))
}
fn place_generated_box(
&mut self,
parent: &Style,
generated: GeneratedBox,
) -> Result<(), DocumentError> {
let GeneratedBox {
mut style,
decoration,
contents,
replacement,
event,
navigation,
element_page_scope,
run_in,
} = generated;
let block_child = std::ptr::eq(parent, self.style);
if run_in {
if block_child {
self.begin_run_in();
}
} else if block_child {
self.resolve_run_in(
if style.position.leaves_flow() || style.floating().is_some() {
RunInFollower::Member
} else {
RunInFollower::Other
},
)?;
}
let page_scope = element_page_scope.as_ref();
if let Some(image) = replacement {
let replaced = Self::generated_block(
style,
Vec::new(),
decoration,
page_scope,
(event, navigation),
);
return self.replaced(replaced, image, parent);
}
if style.display != Display::Contents
&& (style.position.is_out_of_flow() || style.floating().is_some())
{
let children = self.generated_children(&style, contents, FirstLine::default())?;
let shape_outside = self.resources.shape_outside(&style);
let mut generated =
Self::generated_block(style, children, decoration, page_scope, (event, navigation));
generated.shape_outside = shape_outside;
self.out_of_flow(generated);
return Ok(());
}
if style.display.is_list_item() {
self.sheet
.degrade(crate::style::Degradation::InvalidAtComputedValueTime {
declaration: DISPLAY.to_owned(),
reason: GENERATED_LIST_ITEM.to_owned(),
});
style.display = Display::Inline;
}
match &style.display {
Display::Contents => {
if let Some(event) = event {
self.inline.semantic_event(event);
}
self.append_contents(&style, contents)?;
}
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, navigation, false)?;
self.append_contents(&style, contents)?;
self.close_inline()?;
}
display
if matches!(
display,
Display::InlineMath
| Display::InlineBlock
| Display::InlineFlex
| Display::InlineGrid
| Display::InlineTable
) || (display.is_table_part() && self.inline.inside_inline_box()) =>
{
let children = self.generated_children(&style, contents, FirstLine::default())?;
let atomic = Self::generated_block(
style.clone(),
children,
decoration,
page_scope,
(event, navigation),
);
self.atomic(atomic, parent)?;
}
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 = self.generated_children(&style, contents, first_line)?;
let mut generated = Self::generated_block(
style,
children,
decoration,
page_scope,
(event, navigation),
);
generated.enclosing_inline = self.inline.open_boxes();
self.children.push(BlockContent::Block(generated));
}
}
Ok(())
}
fn append_contents(
&mut self,
style: &Style,
contents: GeneratedContents,
) -> Result<(), DocumentError> {
match contents {
GeneratedContents::Output { output, images } => {
self.append_generated(&output, &images, style)
}
GeneratedContents::Markers(markers) => {
for marker in markers {
self.place_generated_box(style, marker)?;
}
Ok(())
}
}
}
fn generated_children(
&mut self,
style: &Style,
contents: GeneratedContents,
first_line: FirstLine,
) -> Result<Vec<BlockContent>, DocumentError> {
match contents {
GeneratedContents::Output { output, images } => {
if style.display.is_block_level_block_container() {
self.first_line_block(first_line, &output, &images, style)
} else {
Ok(Paragraph::generated_output(&output, &images, style)?
.into_iter()
.map(BlockContent::Inline)
.collect())
}
}
GeneratedContents::Markers(markers) => self.marker_children(style, markers, first_line),
}
}
fn marker_children(
&mut self,
style: &Style,
markers: Vec<GeneratedBox>,
mut first_line: FirstLine,
) -> Result<Vec<BlockContent>, DocumentError> {
let page_scope =
crate::document::page::used_name(&style.page, self.element_page_scope.as_ref());
let mut children = Vec::new();
let mut inline = InlineCollector::default();
let mut run_in = None;
let mut letter = None;
let mut ruby = crate::document::ruby::RubyStack::default();
let mut sized = false;
let mut builder = BlockBuilder {
sheet: self.sheet,
element: self.element,
style,
sized: &mut sized,
element_page_scope: &page_scope,
children: &mut children,
inline: &mut inline,
run_in: &mut run_in,
first_line: &mut first_line,
letter: &mut letter,
ruby: &mut ruby,
traversal: &mut *self.traversal,
resources: &mut *self.resources,
};
for marker in markers {
builder.place_generated_box(style, marker)?;
}
builder.resolve_run_in(RunInFollower::Other)?;
builder.flush()?;
mark_last_formatted_line(&mut children);
Ok(children)
}
fn place_marker_group(
&mut self,
element: Element<'_>,
parent: &Style,
mut style: Style,
markers: Vec<GeneratedBox>,
) -> Result<(), DocumentError> {
normalize_child_display(&mut style.display, false, &self.style.display);
let run_in = style.display.run_in().cloned();
if let Some(inner) = run_in.clone() {
style.display = inner;
}
let element_page_scope =
crate::document::page::used_name(&parent.page, self.element_page_scope.as_ref());
let decoration = if style.display == Display::Contents {
BoxDecoration::default()
} else {
self.resources.backgrounds(&style)
};
let navigation = self.traversal.navigation.descendant();
if style.display != Display::Contents && style.position == crate::style::Position::Running {
let name = style
.running
.clone()
.expect("running() names the running element");
let children = self.marker_children(&style, markers, FirstLine::default())?;
let block = Self::generated_block(
style,
children,
decoration,
element_page_scope.as_ref(),
(None, navigation),
);
let event = self.traversal.strings.record_generated_running(
element,
GeneratedPseudoElement::ScrollMarkerGroup,
name,
block,
Vec::new(),
);
self.inline.semantic_event(event);
return Ok(());
}
self.place_generated_box(
parent,
GeneratedBox {
style,
decoration,
contents: GeneratedContents::Markers(markers),
replacement: None,
event: None,
navigation,
element_page_scope,
run_in: run_in.is_some(),
},
)
}
fn first_line_block(
&mut self,
first_line: FirstLine,
output: &crate::style::GeneratedOutput,
images: &[crate::document::inline::GeneratedImage],
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, images, 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 replaced(
&mut self,
mut block: BlockBox,
image: std::sync::Arc<crate::images::Image>,
parent: &Style,
) -> Result<(), DocumentError> {
block.image = Some(image);
if block.style.position.is_out_of_flow() || block.style.floating().is_some() {
self.out_of_flow(block);
} else if block.style.display.is_inline_level() {
self.atomic(block, parent)?;
} else {
self.flush()?;
block.enclosing_inline = self.inline.open_boxes();
self.children.push(BlockContent::Block(block));
}
Ok(())
}
fn element_content(
&mut self,
element: Element<'_>,
style: &Style,
content: &crate::style::GeneratedContent,
) -> Result<(), DocumentError> {
let bound = self.traversal.bind(
content,
crate::style::PageStyleTarget {
element: element.id(),
pseudo: None,
},
false,
)?;
let output = content_output(
self.sheet,
&mut self.traversal.counters,
&bound,
&style.quotes,
&mut self.traversal.quotes,
)?;
let images = self.resources.generated_images(&output, style);
self.append_generated(&output, &images, style)
}
fn generated_copies(
&mut self,
content: &crate::style::GeneratedContent,
context: crate::style::PageStyleTarget,
quotes: &crate::style::Quotes,
depth: crate::style::QuoteDepth,
) -> Result<
Vec<(
crate::document::generated::PageNumbers,
crate::style::GeneratedOutput,
)>,
DocumentError,
> {
if self.traversal.generated.formats_copy() {
return Ok(Vec::new());
}
let pages = self.traversal.generated.running_pages(context).to_vec();
pages
.into_iter()
.map(|numbers| {
let bound = self
.traversal
.generated
.bind_copy(content, context, numbers)?;
let output = content_output(
self.sheet,
&mut self.traversal.counters,
&bound,
quotes,
&mut depth.clone(),
)?;
Ok((numbers, output))
})
.collect()
}
fn running_text_block(
&mut self,
output: &crate::style::GeneratedOutput,
style: Style,
decoration: BoxDecoration,
element_page_scope: Option<&std::sync::Arc<str>>,
) -> Result<BlockBox, DocumentError> {
let images = self.resources.generated_images(output, &style);
let children = Paragraph::generated_output(output, &images, &style)?
.into_iter()
.map(BlockContent::Inline)
.collect();
Ok(Self::generated_block(
style,
children,
decoration,
element_page_scope,
(None, self.traversal.navigation.descendant()),
))
}
fn generated_block(
style: Style,
children: Vec<BlockContent>,
decoration: BoxDecoration,
element_page_scope: Option<&std::sync::Arc<str>>,
(event, navigation): (Option<crate::document::SemanticEvent>, BoxNavigation),
) -> BlockBox {
let page_scope = crate::document::page::used_name(&style.page, element_page_scope);
BlockBox {
navigation,
canvas_source: false,
event,
..BlockBox::with_decoration(style, children, decoration, page_scope)
}
}
}
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 marker = marker.used();
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.bind(
&content,
crate::style::PageStyleTarget {
element: element.id(),
pseudo: Some(PseudoElement::Marker),
},
false,
)?;
let output = content_output(
sheet,
&mut traversal.counters,
&bound,
&marker.quotes,
&mut traversal.quotes,
)?;
let images = resources.generated_images(&output, &used);
Paragraph::generated_marker(&output, &images, &used)
}
fn content_output(
sheet: &Stylesheet,
counters: &mut crate::document::counters::Counters,
bound: &crate::style::GeneratedContent,
quotes: &crate::style::Quotes,
depth: &mut crate::style::QuoteDepth,
) -> Result<crate::style::GeneratedOutput, StyleError> {
let output = bound.element_output_with_counters(
crate::document::MAX_INLINE_TEXT_BYTES,
&mut |request| Ok(counters.text(request)),
quotes,
depth,
)?;
crate::document::content::record_text_limit(sheet.degradations(), output.limited());
Ok(output)
}
fn text_limited<'a>(blocks: impl Iterator<Item = &'a BlockBox>) -> bool {
let mut pending: Vec<&BlockBox> = blocks.collect();
while let Some(block) = pending.pop() {
for child in block.children() {
match child {
BlockContent::Block(child) | BlockContent::Positioned(child) => {
pending.push(child);
}
BlockContent::Inline(paragraph) => {
if paragraph.text_limited() {
return true;
}
pending.extend(
paragraph
.anchors()
.iter()
.chain(paragraph.atomics())
.chain(paragraph.annotations())
.map(crate::document::Anchor::block),
);
}
BlockContent::Events(_) => {}
}
}
}
false
}
fn formatting_depth(style: &Style, parent: &Style, math: bool) -> usize {
if math || style.display == Display::Contents {
return BOX_DEPTH;
}
let display = &style.display;
[
(display.is_atomic_inline(), ATOMIC_INLINE_DEPTH),
(
display.is_table() || generates_anonymous_table(display, &parent.display),
TABLE_DEPTH,
),
(
style.writing_mode.vertical() != parent.writing_mode.vertical()
&& [&style.width, &style.height]
.into_iter()
.any(|size| size.resolve_definite(None).is_none()),
ORTHOGONAL_DEPTH,
),
(display.is_flex(), FLEX_DEPTH),
(display.is_grid(), GRID_DEPTH),
(style.multicol.is_multicol(), MULTICOL_DEPTH),
(style.floating().is_some(), FLOAT_DEPTH),
(style.position.is_out_of_flow(), POSITIONED_DEPTH),
(
style.is_filtered() || style.has_backdrop_filter(),
FILTER_DEPTH,
),
]
.into_iter()
.filter_map(|(applies, depth)| applies.then_some(depth))
.sum::<usize>()
+ BOX_DEPTH
}
fn generates_anonymous_table(display: &Display, parent: &Display) -> bool {
match display {
Display::TableCell => {
!(*parent == Display::TableRow || parent.is_row_group() || parent.is_table())
}
Display::TableRow => !(parent.is_row_group() || parent.is_table()),
part => part.is_table_part() && !parent.is_table(),
}
}
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
&& !matches!(display, Display::InlineMath | Display::BlockMath)
&& (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(|style| style.used())
.map(Box::new)
.map_err(Into::into)
}
#[derive(Clone, Copy)]
enum Placement {
Root,
Flow,
Positioned,
Running,
Footnote,
InlineFootnote,
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<Box<OpenLetter>>,
ruby: crate::document::ruby::RubyStack,
ruby_container: bool,
sizes_letter: bool,
inline_footnote: Option<Box<InlineFootnoteMember>>,
first_line_box: Option<std::rc::Rc<FirstLineBox>>,
own_copy: Option<first_line_copies::OwnCopy>,
}
struct InlineFootnoteMember {
style: Style,
members: Vec<usize>,
start: (usize, crate::document::inline::ContentMark),
}
struct Frame<'d> {
element: Element<'d>,
style: Box<Style>,
page_scope: Option<std::sync::Arc<str>>,
depth: usize,
math_depth: Option<usize>,
nodes: Option<ChildNodes<'d>>,
block: Option<OpenBlock>,
started: bool,
quotes: Option<crate::style::QuoteDepth>,
generated: bool,
ordinal: i128,
scroll_container: bool,
marker_group: Option<Box<Style>>,
}
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,
math_depth: None,
nodes: 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,
sizes_letter: false,
inline_footnote: None,
first_line_box: None,
own_copy: None,
}),
started: false,
quotes: None,
generated: false,
ordinal,
scroll_container: false,
marker_group: None,
}
}
fn copy_root(&self, style: Box<Style>) -> Self {
Self {
scroll_container: self.scroll_container,
marker_group: self.marker_group.clone(),
..Self::new(
self.element,
style,
self.depth,
self.ordinal,
Some(Placement::Root),
self.page_scope.as_ref(),
)
}
}
}
fn hidden<'a>(
child: Element<'_>,
sheet: &'a Stylesheet,
traversal: &mut Traversal<'a>,
resources: &ImageResources<'a>,
) -> Result<Vec<crate::document::SemanticEvent>, DocumentError> {
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(())
})
},
)?;
Ok(events)
}
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,
element: frame.element.id(),
style: &frame.style,
sized: &mut block.sizes_letter,
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,
)
}
#[inline(never)]
fn open_inline_footnote<'d>(
frames: &mut Vec<Frame<'d>>,
(element, style): (Element<'d>, &Style),
parent: usize,
sheet: &Stylesheet,
traversal: &mut Traversal<'_>,
resources: &mut ImageResources<'_>,
) -> Result<(), DocumentError> {
let (block_style, children, inline, members) = match traversal.inline_footnotes.take() {
Some(open) => {
let InlineFootnotes {
style,
children,
inline,
members,
} = *open;
(style, children, inline, members)
}
None => (
Box::new(traversal.inline_footnotes_style(element.id(), sheet, resources)?),
Vec::new(),
InlineCollector::default(),
Vec::new(),
),
};
let mut frame = Frame::new(
element,
block_style,
frames[parent].depth + 1,
0,
Some(Placement::InlineFootnote),
None,
);
frame.started = true;
let block = frame
.block
.as_mut()
.expect("an inline footnote frame builds a block");
block.children = children;
block.inline = inline;
block.inline_footnote = Some(Box::new(InlineFootnoteMember {
style: style.clone(),
members,
start: (block.children.len(), block.inline.content_mark()),
}));
frames.push(frame);
Ok(())
}
#[inline(never)]
fn end_inline_footnote<'a>(
frames: &mut Vec<Frame<'_>>,
parent: usize,
sheet: &'a Stylesheet,
traversal: &mut Traversal<'a>,
resources: &mut ImageResources<'a>,
) -> Result<(), DocumentError> {
let wrapper = frames.pop().expect("the inline footnote's block is open");
let element = wrapper.element;
let mut block = wrapper
.block
.expect("an inline footnote frame builds a block");
let member = block
.inline_footnote
.take()
.expect("an inline footnote block holds its footnote");
let index = traversal.add_footnote(element.id(), &member.style);
let order = traversal.strings.event(element, None, false).order;
let (children, mark) = member.start;
let mark = if block.children.len() == children {
mark
} else {
crate::document::inline::ContentMark::default()
};
let mut events = Vec::new();
let visited = content_events(&block.children[children..], &mut events)
+ block.inline.content_events_after(mark, &mut events);
traversal.work.charge(visited + events.len());
events.retain(|event| order.contains(&event.order.start));
events.sort_by_key(|event| event.order.start);
let events: Vec<_> = events.into_iter().cloned().collect();
let (mut builder, _) = active_builder(frames, parent, sheet, traversal, resources);
builder.footnote_call(element, &member.style, events.iter().collect(), index)?;
traversal.finish_inline_footnotes()?;
let mut members = member.members;
members.push(index);
traversal.inline_footnotes = Some(Box::new(InlineFootnotes {
style: wrapper.style,
children: block.children,
inline: block.inline,
members,
}));
Ok(())
}
fn block<'a>(
root: Frame<'a>,
sheet: &'a Stylesheet,
traversal: &mut Traversal<'a>,
resources: &mut ImageResources<'a>,
) -> Result<BlockBox, DocumentError> {
let element = root.element;
let mut frames = vec![root];
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 mut block_index = *blocks.last().unwrap();
if !frames[index].started {
traversal.work.charge(ELEMENT_WORK);
let (first_line, own_copy) = match (blocks.len().checked_sub(2), &frames[index].block) {
(Some(parent), Some(block)) if matches!(block.placement, Placement::Atomic) => {
first_line_copies::atomic_first_line(
&mut frames,
blocks[parent],
sheet,
traversal,
resources,
)?
}
_ => (None, None),
};
let scroller = marker_scroller(&frames[..index], traversal);
let frame = &mut frames[index];
if let Some(block) = &mut frame.block {
block.first_line_box = first_line;
block.own_copy = own_copy;
}
let element = frame.element;
frame.quotes = frame.style.containment().style.then_some(traversal.quotes);
traversal.generated.capture(element, &traversal.counters);
let copies = if frame
.block
.as_ref()
.is_some_and(|block| matches!(block.placement, Placement::Running))
{
running_copies((frame, scroller), sheet, traversal, resources)?
} else {
Vec::new()
};
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 = canvas_background(&block.decoration);
}
let replacement = if skips {
None
} else {
frame
.style
.content_replacement()
.map(|image| resources.replacement_image(image, &frame.style))
};
let control = if skips || replacement.is_some() {
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 if replacement.is_some() {
replacement
} else {
match element.name() {
"img" => {
let image = sheet.image_source(element).and_then(|source| {
block.density = source.density.unwrap_or(DEFAULT_DENSITY);
resources
.cache
.load_optional(
&source.url,
resources.base,
resources.resolver,
frame.style.element_font_namespace(),
)
.map(|image| {
crate::images::content_image(
image,
&frame.style,
source.density,
)
})
});
if image.is_none()
&& !skips
&& let Some(alt) = element.attr("alt")
{
block.inline.append(alt, &frame.style);
}
image
}
"svg" => {
let resolver = resources.resolver;
let image = crate::document::svg::serialize(
element,
&frame.style,
&crate::document::svg::Styling {
sheet,
resolver,
work: &traversal.work,
},
&mut |style| resources.masks(style),
)
.and_then(|svg| {
Ok(resources.cache.inline_svg_in_namespace(
svg.xml,
svg.styling,
resources.base,
resolver,
frame.style.element_font_namespace(),
)?)
});
match image {
Ok(image) => Some(image),
Err(error) => {
sheet.degrade(crate::style::Degradation::SvgInError {
reason: error.to_string(),
});
None
}
}
}
"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) => {
crate::images::content_image(image.clone(), &frame.style, None)
}
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 mut assignment = traversal.strings.record(
element,
&frame.style.string_set,
&mut traversal.counters,
block.marker.as_ref().map(Paragraph::text),
)?;
if let (Placement::Running, Some(name)) = (block.placement, &frame.style.running) {
assignment = Some(traversal.strings.record_running(
element,
assignment,
name.clone(),
copies,
));
}
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 = traversal.canvas_source(index, element);
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" {
let footnote = frames[index]
.block
.as_ref()
.is_some_and(|block| matches!(block.placement, Placement::Footnote))
|| index
.checked_sub(1)
.and_then(|wrapper| frames[wrapper].block.as_ref())
.is_some_and(|block| block.inline_footnote.is_some());
let root_group = root_marker_group(
&frames,
index,
traversal,
crate::style::ScrollMarkerGroup::Before,
);
let root_markers = match root_group {
Some(_) => Some(collect_scroll_markers(
frames[0].copy_root(frames[0].style.clone()),
sheet,
traversal,
resources,
)?),
None => None,
};
let (mut builder, style) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
if let (Some(group), Some(markers)) = (root_group, root_markers) {
builder.place_marker_group(element, style, group, markers)?;
}
if footnote {
builder.generated(element, style, GeneratedPseudoElement::FootnoteMarker)?;
}
if element.generates_checkmark() {
builder.generated(element, style, GeneratedPseudoElement::Checkmark)?;
}
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(content) = style.content_list() {
builder.element_content(element, style, content)?;
for child in element.children(TreeRelation::Formatting) {
for event in hidden(child, sheet, builder.traversal, builder.resources)?
{
builder.inline.semantic_event(event);
}
}
} else {
frames[index].nodes = Some(element.child_nodes(TreeRelation::Formatting));
}
}
}
frames[index].started = true;
continue;
}
if let Some(node) = frames[index].nodes.as_mut().and_then(Iterator::next) {
let block_child = frames[block_index + 1..=index]
.iter()
.all(|frame| frame.style.display == Display::Contents);
if traversal.work.exhausted().is_some() {
continue;
}
if let Some(text) = node.value().as_text() {
traversal.work.charge(text.len().max(1));
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 {
canvas_background(&resources.backgrounds(&child_style))
};
}
let replaced = is_replaced(child) || child_style.content_replacement().is_some();
if replaced && child_style.display == Display::Contents {
child_style.display = Display::None;
}
let math_depth = frames[index]
.math_depth
.map(|depth| depth + 1)
.or_else(|| (child.namespace() == crate::dom::MATHML_NAMESPACE).then_some(0));
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);
let parent_style = &frames[block_index].style;
let exceeded = if frames[index].depth
+ formatting_depth(&child_style, parent_style, math_depth.is_some())
> MAX_FORMATTING_DEPTH
{
Some((FORMATTING_NESTING_RESOURCE, MAX_FORMATTING_DEPTH))
} else if math_depth.is_some_and(|depth| depth >= crate::document::mathml::MAX_DEPTH) {
Some((MATHML_NESTING_RESOURCE, crate::document::mathml::MAX_DEPTH))
} else {
None
};
if let Some(limit) = exceeded
&& !replaced
&& child_style.display != Display::None
{
child_style.display = Display::Contents;
traversal.flattened.insert(limit);
}
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 events = hidden(child, sheet, traversal, resources)?;
let (builder, _) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
for event in events {
builder.inline.semantic_event(event);
}
continue;
}
let counters = if child_style.footnote() && child_style.display != Display::Contents {
child_style
.counters
.with_implicit_increment(crate::style::FOOTNOTE_COUNTER)
} else {
child_style.counters.clone()
};
traversal.counters.prepare(
&counters,
traversal.document,
sheet,
&traversal.root_style,
resources.resolver,
)?;
traversal.counters.enter_at_pages(
crate::style::PageStyleTarget {
element: child.id(),
pseudo: None,
},
&counters,
&child_style.display,
child_style.containment().style,
traversal.generated.page_starts(child.id()),
&mut traversal.page_counters,
)?;
let child_depth = frames[index].depth
+ formatting_depth(
&child_style,
&frames[block_index].style,
math_depth.is_some(),
);
let ancestor_page = frames[index].page_scope.clone();
let math_cell = crate::document::mathml::table::is_cell(
frames[block_index].element,
&frames[block_index].style.display,
);
if child_style.footnote() && child_style.display != Display::Contents {
let inline = child_style.footnote_display == crate::style::FootnoteDisplay::Inline;
if !inline || traversal.generated.starts_inline_footnotes(child.id()) {
traversal.finish_inline_footnotes()?;
}
if inline {
open_inline_footnote(
&mut frames,
(child, &child_style),
index,
sheet,
traversal,
resources,
)?;
block_index = frames.len() - 1;
blocks.push(block_index);
child_style.float = crate::style::Float::None;
}
}
scroll_marker(
&mut frames,
block_index,
(child, &child_style),
sheet,
traversal,
resources,
)?;
let scroll_container = child_style.scroll_container_box(replaced);
record_scroll_marker_box(&frames, (child, &child_style), scroll_container, traversal);
let marker_group = if scroll_container {
marker_group_style(child, &child_style, sheet, resources.resolver)?
} else {
None
};
if let Some(group) = marker_group.as_deref().filter(|_| {
child_style.scroll_markers.group == crate::style::ScrollMarkerGroup::Before
&& !traversal.marker_prepass
}) {
let mut frame = Frame::new(
child,
child_style.clone(),
child_depth,
0,
Some(Placement::Root),
ancestor_page.as_ref(),
);
frame.scroll_container = true;
frame.marker_group = Some(Box::new(group.clone()));
let markers = collect_scroll_markers(frame, sheet, traversal, resources)?;
let (mut builder, parent) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
builder.place_marker_group(child, parent, group.clone(), markers)?;
}
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.leaves_flow()
|| child_style.floating().is_some()
|| child_style.footnote()
{
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;
}
if child_style.display == Display::Inline
&& builder
.ruby
.annotation_mode()
.is_some_and(|mode| mode != child_style.used_writing_mode())
{
child_style.display = Display::InlineBlock;
}
let placement = if child_style.display == Display::Contents {
None
} else if child_style.position == crate::style::Position::Running {
Some(Placement::Running)
} else if child_style.footnote() {
Some(Placement::Footnote)
} 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::BlockMath
| 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 => {
if child_style.display.is_table_part() && builder.inline.inside_inline_box()
{
Some(Placement::Atomic)
} else {
builder.flush()?;
Some(Placement::Flow)
}
}
Display::InlineMath | Display::InlineTable
if (matches!(
builder.style.display,
Display::BlockMath | Display::InlineMath
) || math_cell)
&& !child_style.inlinified() =>
{
builder.flush()?;
Some(Placement::Flow)
}
Display::InlineMath
| 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
}
}
};
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());
}
if matches!(placement, Some(Placement::Running)) {
traversal.running.push(crate::style::PageStyleTarget {
element: child.id(),
pseudo: None,
});
}
frames.push(Frame::new(
child,
child_style,
child_depth,
ordinal,
placement,
ancestor_page.as_ref(),
));
let frame = frames.last_mut().expect("the child frame was appended");
frame.math_depth = math_depth;
frame.scroll_container = scroll_container;
frame.marker_group = marker_group;
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;
if frames[index]
.block
.as_ref()
.is_some_and(|block| block.inline_footnote.is_some())
{
blocks.pop();
let parent = *blocks
.last()
.expect("an inline footnote has a containing block");
end_inline_footnote(&mut frames, parent, sheet, traversal, resources)?;
continue;
}
let generated = frames[index].generated;
let contents = frames[index].style.display == Display::Contents;
let quotes = frames[index].quotes;
let root_group = root_marker_group(
&frames,
index,
traversal,
crate::style::ScrollMarkerGroup::After,
);
let (mut builder, style) =
active_builder(&mut frames, block_index, sheet, traversal, resources);
if generated {
builder.generated(element, style, GeneratedPseudoElement::After)?;
if element.generates_picker_icon() {
builder.generated(element, style, GeneratedPseudoElement::PickerIcon)?;
}
}
if let Some(group) = root_group {
let markers = builder
.traversal
.scroll_markers
.remove(&element.id())
.unwrap_or_default();
builder.place_marker_group(element, style, group, markers)?;
}
if let Some(depth) = quotes {
builder.traversal.quotes = depth;
}
if index != block_index {
if contents {
builder.inline.close_contents();
} else {
builder.inline.prepare_math_inline(element, style);
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 mut frame = frames.pop().unwrap();
blocks.pop();
let marker_group = frame.marker_group.take();
let marker_side = frame.style.scroll_markers.group;
let scroll_container = frame.scroll_container;
let mut state = frame.block.unwrap();
mark_last_formatted_line(&mut state.children);
let canvas_source = traversal.canvas_source(index, element);
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.first_line_box = state.first_line_box;
block.own_copy = state.own_copy;
block.navigation = state.navigation;
block.event = state.event;
block.canvas_source = canvas_source;
block.query_container =
(block.style.containment().query_container || state.sizes_letter).then(|| element.id());
if crate::document::mathml::table::is_cell(element, &block.style().display) {
let children = std::mem::take(&mut block.children);
block.children = crate::document::mathml::table::cell(
block.style(),
children,
sheet,
resources.resolver,
)?;
}
crate::document::mathml::prepare(element, &mut block, sheet, resources.resolver)?;
if matches!(state.placement, Placement::Root) {
return Ok(block);
}
let mut markers = scroll_container
.then(|| traversal.scroll_markers.remove(&element.id()))
.flatten();
if traversal.marker_prepass
&& marker_group.is_some()
&& marker_side == crate::style::ScrollMarkerGroup::Before
{
traversal
.prepassed_markers
.insert(element.id(), markers.take().unwrap_or_default());
}
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::Running => {
builder.traversal.running.pop();
builder.running(element, block);
}
Placement::Footnote => builder.footnote(element, block)?,
Placement::InlineFootnote => {
unreachable!("inline footnote blocks finish as their footnotes end")
}
Placement::Atomic => builder.atomic(block, parent)?,
Placement::Root => unreachable!("root returned before attaching to a parent"),
}
if let Some(group) = marker_group.filter(|_| {
marker_side == crate::style::ScrollMarkerGroup::After
&& !builder.traversal.marker_prepass
}) {
builder.place_marker_group(element, parent, *group, markers.unwrap_or_default())?;
}
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 elements: &'a crate::document::element_images::ElementMeasurements,
pub definitions: &'a crate::document::svg::SvgDefinitions,
pub work_limit: usize,
}
pub(crate) fn build(
input: &Input<'_>,
sheet: &mut Stylesheet,
(base, resolver): (
&crate::resources::ResourceBase,
&dyn crate::resources::ResourceResolver,
),
navigation: &dyn Fn() -> Result<NavigationBuilder, DocumentError>,
values: crate::document::generated::GeneratedValues,
) -> Result<Formatted, DocumentError> {
let copies = sheet.has_pseudo_rules(PseudoElement::FirstLine);
let formatted = format(
input,
sheet,
(base, resolver),
navigation()?,
(values.clone(), copies),
)?;
match formatted.truncated {
Some(limit) if copies => {
let mut formatted = format(
input,
sheet,
(base, resolver),
navigation()?,
(values, false),
)?;
formatted.skipped_work = Some(limit);
Ok(formatted)
}
_ => Ok(formatted),
}
}
fn format(
input: &Input<'_>,
sheet: &mut Stylesheet,
(base, resolver): (
&crate::resources::ResourceBase,
&dyn crate::resources::ResourceResolver,
),
navigation: NavigationBuilder,
(values, first_line_copies): (crate::document::generated::GeneratedValues, bool),
) -> Result<Formatted, DocumentError> {
sheet.anchor_nodes.borrow_mut().clear();
let generated = crate::document::generated::GeneratedPass::new(
navigation.targets.clone(),
values,
sheet.degradations().clone(),
);
let mut style = root_style(input.html, sheet, resolver, &generated)?;
input.images.borrow_mut().adopt_palettes(&sheet.fonts);
let sheet = &*sheet;
let elements = std::rc::Rc::new(crate::document::element_images::ElementImages::new(
input.html,
sheet,
navigation.targets.clone(),
input.elements.clone(),
input.definitions,
));
let resources = Resources {
base,
resolver,
elements: &elements,
};
let pages = first_pages(input, sheet, &style, &resources, generated.bindings())?;
*style = style.used();
if style.display == Display::None {
hidden_root(
input, sheet, &style, &resources, navigation, generated, pages,
)
} else {
format_root(
input,
sheet,
style,
&resources,
navigation,
(generated, first_line_copies),
pages,
)
}
}
struct Resources<'r> {
base: &'r crate::resources::ResourceBase,
resolver: &'r dyn crate::resources::ResourceResolver,
elements: &'r std::rc::Rc<crate::document::element_images::ElementImages>,
}
fn root_style(
html: &DocumentTree,
sheet: &mut Stylesheet,
resolver: &dyn crate::resources::ResourceResolver,
generated: &crate::document::generated::GeneratedPass,
) -> Result<Box<Style>, DocumentError> {
sheet
.resolve_document_root_with_pages(
html,
resolver,
&|styles, groups| {
crate::document::first_page::select_name(html, styles, generated, groups)
},
&|styles| crate::document::first_page::select_side(html, styles, generated),
)
.map(Box::new)
.map_err(DocumentError::Style)
}
fn first_pages(
input: &Input<'_>,
sheet: &Stylesheet,
root: &Style,
resources: &Resources<'_>,
bindings: crate::document::generated::GeneratedBindings,
) -> Result<crate::document::page::PageProvider, DocumentError> {
let area = sheet.page_content_box();
let resolved = sheet.resolve_page(
root,
sheet.first_page_request().clone(),
Some([area.width, area.height]),
resources.resolver,
)?;
let mut cache = input.images.borrow_mut();
let mut images = ImageResources {
base: resources.base,
resolver: resources.resolver,
cache: &mut cache,
elements: resources.elements,
};
let page = PageBox::load(resolved, &mut images, &bindings)?;
Ok(crate::document::page::PageProvider::new(
page,
input.images.clone(),
resources.base.clone(),
bindings,
resources.elements.clone(),
))
}
fn hidden_root(
input: &Input<'_>,
sheet: &Stylesheet,
style: &Style,
resources: &Resources<'_>,
navigation: NavigationBuilder,
mut generated: crate::document::generated::GeneratedPass,
pages: crate::document::page::PageProvider,
) -> Result<Formatted, DocumentError> {
let html = input.html;
let resolver = resources.resolver;
let element = html.root_element();
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 mut cache = input.images.borrow_mut();
let linked = cache.linked_documents();
let mut images = ImageResources {
base: resources.base,
resolver,
cache: &mut cache,
elements: resources.elements,
};
let work = crate::layout::work::Budget::new(input.work_limit);
let svg_definitions = crate::document::svg::SvgDefinitions::collect(
html,
style,
&crate::document::svg::Styling {
sheet,
resolver,
work: &work,
},
linked,
&mut |style| images.masks(style),
)?;
Ok(Formatted {
root: BlockBox::anonymous(style.clone(), vec![BlockContent::Events(events)], None),
footnotes: Footnotes::default(),
navigation,
strings,
generated: generated.finish(),
canvas,
pages,
svg_definitions,
page_counters: Vec::new(),
scroll_markers: crate::document::scroll_markers::ScrollMarkerGroups::default(),
skipped_work: work.declined(),
diagnostics: Vec::new(),
truncated: None,
})
}
fn format_root(
input: &Input<'_>,
sheet: &Stylesheet,
mut style: Box<Style>,
resources: &Resources<'_>,
navigation: NavigationBuilder,
(generated, first_line_copies): (crate::document::generated::GeneratedPass, bool),
pages: crate::document::page::PageProvider,
) -> Result<Formatted, DocumentError> {
let Input {
html,
embedded,
images,
..
} = *input;
let resolver = resources.resolver;
let element = html.root_element();
let mut cache = images.borrow_mut();
let mut resources = ImageResources {
base: resources.base,
resolver,
cache: &mut cache,
elements: resources.elements,
};
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(),
footnotes: Footnotes::default(),
inline_footnotes: None,
page_counters: Vec::new(),
running: Vec::new(),
pages: &pages,
scroll_markers: std::collections::HashMap::new(),
marker_prepass: false,
prepassed_markers: std::collections::HashMap::new(),
marker_scroller: None,
marker_groups: crate::document::scroll_markers::ScrollMarkerGroups::default(),
work: crate::layout::work::Budget::new(input.work_limit),
kind: TraversalKind::Document,
first_lines: std::rc::Rc::new(std::cell::RefCell::new(
first_line_copies::FirstLineCopies::new(first_line_copies),
)),
requests: Vec::new(),
flattened: std::collections::BTreeSet::new(),
canvas_body: (style.decoration.background.alpha == 0.0
&& !style.decoration.backgrounds.has_images())
.then(|| html.body_element().map(Element::id))
.flatten(),
};
let counters = style
.counters
.with_implicit_reset(crate::style::FOOTNOTE_COUNTER);
traversal
.counters
.prepare(&counters, html, sheet, &style, resolver)?;
traversal.counters.enter(
crate::style::PageStyleTarget {
element: element.id(),
pseudo: None,
},
&counters,
&style.display,
style.containment().style,
)?;
traversal.counters.start_pages(
traversal.generated.page_starts(element.id()).iter(),
&mut traversal.page_counters,
);
let ordinal = if style.display.is_list_item() {
traversal.counters.ordinal()
} else {
0
};
let surface = surface_beneath(sheet, &style);
let linked = resources.cache.linked_documents();
let svg_definitions = crate::document::svg::SvgDefinitions::collect(
html,
&style,
&crate::document::svg::Styling {
sheet,
resolver,
work: &traversal.work,
},
linked,
&mut |style| resources.masks(style),
)?;
let marker_group = marker_group_style(element, &style, sheet, resolver)?;
traversal.marker_groups.scroller(element.id(), None, &style);
traversal.marker_groups.element(element.id(), element.id());
if traversal.navigation.is_scroll_target(element.id()) {
traversal.marker_groups.target(element.id(), &style);
}
let mut root = block(
Frame {
scroll_container: true,
marker_group,
..Frame::new(element, style, 0, ordinal, Some(Placement::Root), None)
},
sheet,
&mut traversal,
&mut resources,
)?;
traversal.finish_inline_footnotes()?;
root.trim_text_boxes([false; 2]);
for block in traversal.strings.running_blocks_mut().chain(
traversal
.footnotes
.bodies
.iter_mut()
.map(|body| &mut body.block),
) {
block.trim_text_boxes([false; 2]);
}
if let Some(body) = html.body_element() {
let principal = sheet.computed_with_resolver(body, root.style(), resolver)?;
root.style.principal_flow = Some(crate::style::logical::Flow::of(&principal));
}
root.reflow(crate::style::logical::Flow::used(root.style()));
for block in traversal.strings.running_blocks_mut().chain(
traversal
.footnotes
.bodies
.iter_mut()
.map(|body| &mut body.block),
) {
block.reflow(crate::style::logical::Flow::used(root.style()));
}
let initials = traversal.counters.page_initials();
traversal.generated.page_initials(initials);
let counters_exhausted = traversal.counters.exhausted();
let text_limited = text_limited(
std::iter::once(&root)
.chain(traversal.strings.running_blocks_mut().map(|block| &*block))
.chain(traversal.footnotes.bodies.iter().map(|body| &body.block)),
);
let Traversal {
footnotes,
navigation,
strings,
generated,
canvas,
page_counters,
marker_groups,
work,
flattened,
..
} = traversal;
let truncated = work.exhausted();
let diagnostics = flattened
.into_iter()
.map(|(resource, limit)| (resource, limit, FLATTENED_NESTING))
.chain(truncated.map(|limit| (FORMATTING_WORK_RESOURCE, limit, TRUNCATED_CONTENT)))
.chain(text_limited.then_some((
TEXT_LIMIT_RESOURCE,
crate::document::MAX_INLINE_TEXT_BYTES,
LIMITED_TEXT,
)))
.chain(counters_exhausted.then_some((
crate::document::counters::COUNTER_WORK_RESOURCE,
crate::document::counters::MAX_COUNTER_WORK,
UNEVALUATED_COUNTERS,
)))
.map(
|(resource, limit, fallback)| crate::document::DocumentDiagnostic::FormattingLimit {
resource,
limit,
fallback,
},
)
.collect();
Ok(Formatted {
root,
footnotes,
navigation,
strings,
generated: generated.finish(),
canvas: canvas_surface(canvas, surface),
pages,
svg_definitions,
page_counters,
scroll_markers: marker_groups,
skipped_work: work.declined(),
diagnostics,
truncated,
})
}
#[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:?}");
}
}
}
}