#[allow(
clippy::wildcard_imports,
reason = "pagination submodules extend the parent paginator and share its scope"
)]
use super::*;
#[derive(Clone, Copy)]
struct LineGeometry {
x: f32,
width: f32,
y: f32,
}
enum FloatTrial {
Float { anchor: usize, line: usize, y: f32 },
Letter {
side: crate::style::FloatSide,
margin: Rect,
},
}
impl FloatTrial {
fn line(&self) -> usize {
match self {
Self::Float { line, .. } => *line,
Self::Letter { .. } => 0,
}
}
}
struct ParagraphFragment<'a> {
cursor: Box<ParagraphCursor<'a, 'a>>,
take: usize,
request: BreakRequest,
float_anchors: Vec<&'a crate::document::Anchor>,
fragment_trim: [bool; 2],
}
struct FragmentLine {
line: crate::text::Line,
x: f32,
width: f32,
offset: f32,
baseline: f32,
end_trim: f32,
footnotes: Vec<usize>,
}
#[derive(Clone)]
pub(super) struct ParagraphCursor<'a, 't> {
index: usize,
source: &'a crate::document::Paragraph,
style: &'a crate::style::Style,
prepared: Option<Rc<crate::text::PreparedParagraph<'a, 't, 't>>>,
positions: std::vec::IntoIter<crate::text::TextPosition<'a>>,
position: crate::text::TextPosition<'a>,
lines: std::vec::IntoIter<crate::text::Line>,
x: f32,
width: f32,
containing_height: Option<f32>,
candidate_complete: bool,
candidate_page: usize,
geometry: VecDeque<LineGeometry>,
anchors: std::iter::Peekable<std::vec::IntoIter<crate::layout::measure::LineAnchor<'a>>>,
atomics: Vec<Option<crate::layout::inline::MeasuredAtomic<'a>>>,
metrics: Vec<crate::text::AtomicMetrics>,
first_line_atomics: Vec<Option<crate::layout::inline::MeasuredAtomic<'a>>>,
first_line_metrics: Vec<crate::text::AtomicMetrics>,
consumed_anchors: usize,
consumed_events: usize,
consumed_floats: usize,
line_index: usize,
layers: InlineLayers<'a>,
clamp: Option<crate::text::ParagraphClamp>,
letter: Option<usize>,
started: bool,
}
fn letter_exclusion(
extent: crate::layout::inline::LetterExtent,
width: f32,
fragment: &crate::text::AtomicFragment,
line: &crate::text::Line,
placement: LineGeometry,
rtl: bool,
) -> Option<(crate::style::FloatSide, Rect)> {
let x = placement.x + line.alignment_offset(placement.width, rtl) + fragment.x;
let top = placement.y + line.height;
let bottom = placement.y + extent.bottom;
let side = if rtl {
crate::style::FloatSide::Right
} else {
crate::style::FloatSide::Left
};
(bottom > top).then_some((
side,
Rect {
x: if rtl { x } else { x - extent.kerning },
y: top,
width: width + extent.kerning,
height: bottom - top,
},
))
}
impl<'a> Paginator<'a, '_, 'a> {
fn place_inline_float(
&mut self,
measured: floats::MeasuredFloat<'a>,
anchor: &crate::document::Anchor,
geometry: [f32; 3],
layers: &InlineLayers<'a>,
) -> Result<(), LayoutError> {
let chain = inline_chain(layers.paragraph, anchor.inline_box);
let chain_layers = self.chain_layers(&chain, layers.containing);
let saved_context = self.context.clone();
let saved_key = self.key.clone();
let saved_group = self.group;
let saved_clip = self.clip;
let saved_offset = self.offset;
let saved_has_flow = self.has_flow;
if let Some(layer) = chain_layers.last() {
self.context = layer.context.clone();
self.key = layer.key.clone();
self.group = layer.group;
self.clip = layer.clip;
self.offset[0] += layer.offset[0];
self.offset[1] += layer.offset[1];
}
let opened = self.open_inline_containers(&chain, &chain_layers);
self.has_flow |= geometry[2] > self.y;
let result = self.place_measured_float(measured, geometry[0], geometry[1], geometry[2]);
self.close_inline_containers(&opened);
self.context = saved_context;
self.key = saved_key;
self.group = saved_group;
self.clip = saved_clip;
self.offset = saved_offset;
self.has_flow = saved_has_flow;
result
}
fn place_letter_trial(
&mut self,
letter: Option<usize>,
(source, atomics, first_line): InlineBlocks<'_, 'a>,
line: &crate::text::Line,
placement: LineGeometry,
rtl: bool,
trials: &mut Vec<FloatTrial>,
) {
let Some(index) = letter else {
return;
};
if trials
.iter()
.any(|trial| matches!(trial, FloatTrial::Letter { .. }))
{
return;
}
let atomic = letter_atomic(source, atomics, first_line, index)
.expect("the initial letter is measured until its line is placed");
let fragment = line
.atomics
.iter()
.find(|fragment| fragment.index == index)
.expect("the initial letter lies on the first line");
if let Some((side, margin)) = letter_exclusion(
atomic.letter.expect("an initial letter has an extent"),
atomic.metrics.width,
fragment,
line,
placement,
rtl,
) {
self.floats
.last_mut()
.expect("flow has a float context")
.insert_letter(self.page, side, margin);
trials.push(FloatTrial::Letter { side, margin });
}
}
fn remeasure_inline_blocks(
&mut self,
source: &'a crate::document::Paragraph,
(atomics, first_line): (
&mut [Option<crate::layout::inline::MeasuredAtomic<'a>>],
&mut [Option<crate::layout::inline::MeasuredAtomic<'a>>],
),
width: f32,
height: Option<f32>,
) -> Result<(), LayoutError> {
let rtl = source.style().used_rtl();
let blocks =
atomics
.iter_mut()
.enumerate()
.map(|(index, atomic)| (atomic, source.inline_block(index).block()))
.chain(first_line.iter_mut().zip(source.inline_blocks()).map(
|(atomic, anchor)| {
(
atomic,
anchor.block().first_line_box().unwrap_or(anchor.block()),
)
},
));
for (atomic, block) in blocks {
if atomic.is_some() {
*atomic = Some(self.measurer.run(|measurer| {
crate::layout::inline::measure(measurer, block, width, height, rtl)
})?);
}
}
Ok(())
}
fn fit_float_line(
&self,
prepared: &crate::text::PreparedParagraph<'a, 'a, 'a>,
position: crate::text::TextPosition<'a>,
(metrics, first_line_metrics): (
&[crate::text::AtomicMetrics],
&[crate::text::AtomicMetrics],
),
bounds: [f32; 2],
mut y: f32,
) -> Result<
Option<(
crate::text::Line,
crate::text::TextPosition<'a>,
LineGeometry,
)>,
LayoutError,
> {
let context = self.floats.last().expect("flow has a float context");
let mut height = 0.0f32;
loop {
self.measurer.work.spend(metrics.len().max(1))?;
let (band, met) =
context.line_band(self.page, y, height, bounds, &self.measurer.work)?;
let width = (band[1] - band[0]).max(0.0);
let mut lines = prepared
.lines_in_block(
position,
width,
bounds[1] - bounds[0],
[band[0] - bounds[0], bounds[1] - band[1]],
metrics,
)?
.with_first_line_atomics(first_line_metrics)?;
let Some(line) = lines.next() else {
return Ok(None);
};
let line = line?;
self.measurer.work.spend(line.range.len().max(1))?;
if line.height > height {
height = line.height;
continue;
}
if line.width + line.indent > width && met {
y = context.line_fit(
self.page,
y,
height,
bounds,
line.width + line.indent,
&self.measurer.work,
)?;
height = 0.0;
continue;
}
return Ok(Some((
line,
lines.checkpoint(),
LineGeometry {
x: band[0],
width,
y,
},
)));
}
}
pub(super) fn paragraph_break(&mut self) -> Option<BreakRequest> {
let scope = self
.boxes
.iter()
.rev()
.find_map(|active| active.page_scope.clone());
let changed = scope.is_some_and(|name| self.page_name(name, &[]));
Forced::combine(self.pending_break, changed.then_some(Forced::Page))
.filter(|_| self.unbroken == 0 && self.has_flow)
.map(|forced| BreakRequest {
forced: Some(forced),
preserve_empty: false,
})
}
pub(super) fn start_paragraph(
&mut self,
paragraph: MeasuredParagraph<'a>,
) -> ParagraphCursor<'a, 'a> {
if !paragraph.is_phantom() {
self.pending_break = None;
self.flush_margin();
}
let prepared = None;
let mut positions = paragraph.positions.into_iter();
let position = positions
.next()
.expect("paragraph measurement has a start checkpoint");
let lines = paragraph.lines.into_iter();
let x = paragraph.x;
let width = paragraph.width;
let containing_height = paragraph.containing_height;
let candidate_complete = true;
let candidate_page = self.page;
let style = paragraph.style;
let mut anchors = paragraph.anchors.into_iter().peekable();
let atomics = paragraph.atomics;
let mut metrics = Vec::new();
crate::layout::inline::paragraph_metrics(paragraph.paragraph, &atomics, &mut metrics);
let first_line_atomics = paragraph.first_line_atomics;
let mut first_line_metrics = Vec::new();
crate::layout::inline::first_line_metrics(
paragraph.paragraph,
&metrics,
&first_line_atomics,
&mut first_line_metrics,
);
let consumed_anchors = 0;
let consumed_events = 0;
let line_index = 0;
let layers = InlineLayers::new(
paragraph.paragraph,
InlineContaining {
width,
height: containing_height,
rtl: style.used_rtl(),
},
);
if lines.as_slice().is_empty() {
for anchor in anchors.by_ref() {
self.line_anchor(&anchor, x, width, 0.0, 0.0, &layers);
}
}
let source = paragraph.paragraph;
let index = paragraph.index;
let clamp = paragraph.clamp;
let letter = source
.atomics()
.first()
.filter(|atomic| atomic.offset == 0 && atomic.block().initial_letter().is_some())
.map(|_| 0);
ParagraphCursor {
index,
source,
style,
prepared,
positions,
position,
lines,
x,
width,
containing_height,
candidate_complete,
candidate_page,
geometry: VecDeque::new(),
anchors,
atomics,
metrics,
first_line_atomics,
first_line_metrics,
consumed_anchors,
consumed_events,
consumed_floats: 0,
line_index,
layers,
clamp,
letter,
started: false,
}
}
#[inline(never)]
fn fit_paragraph_lines(
&mut self,
cursor: &mut ParagraphCursor<'a, 'a>,
reserve: f32,
(float_anchors, has_inline_floats): (&[&'a crate::document::Anchor], bool),
trials: &mut Vec<FloatTrial>,
) -> Result<(), LayoutError> {
let text = self.measurer.text;
let source = cursor.source;
let style = cursor.style;
let letter = cursor.letter;
let consumed_floats = cursor.consumed_floats;
let consumed_anchors = cursor.consumed_anchors;
let (left, destination_width, height) =
self.paragraph_geometry()
.unwrap_or((cursor.x, cursor.width, cursor.containing_height));
cursor.x = left;
let floating = has_inline_floats
|| !self
.floats
.last()
.expect("flow has a float context")
.is_empty();
if floating
|| cursor.width != destination_width
|| (!cursor.atomics.is_empty() && cursor.containing_height != height)
|| (!cursor.candidate_complete && cursor.candidate_page != self.page)
{
cursor.width = destination_width;
cursor.containing_height = height;
self.remeasure_inline_blocks(
source,
(&mut cursor.atomics, &mut cursor.first_line_atomics),
cursor.width,
height,
)?;
crate::layout::inline::paragraph_metrics(source, &cursor.atomics, &mut cursor.metrics);
crate::layout::inline::first_line_metrics(
source,
&cursor.metrics,
&cursor.first_line_atomics,
&mut cursor.first_line_metrics,
);
if cursor.prepared.is_none() {
self.measurer.work.spend(source.text().len().max(1))?;
}
self.measurer.work.spend(cursor.metrics.len().max(1))?;
let prepared = cursor.prepared.get_or_insert_with(|| {
Rc::new(text.prepare_paragraph(source).clamped(cursor.clamp.clone()))
});
let mut stream = prepared
.lines(cursor.position, cursor.width, &cursor.metrics)?
.with_first_line_atomics(&cursor.first_line_metrics)?;
cursor.geometry.clear();
let mut float_position = cursor.position;
let mut remainder = Vec::new();
let mut checkpoints = Vec::new();
cursor.candidate_complete = true;
cursor.candidate_page = self.page;
let mut extent = self.y + reserve;
let mut available: usize = 0;
let mut overflow = false;
let mut line_clearance_y = None;
loop {
let (line, checkpoint) = if floating {
let cleared_y = if let Some(y) = line_clearance_y {
y
} else {
let (clear, rtl) = source.clearance_at(float_position.offset());
let y = self
.floats
.last()
.expect("flow has a float context")
.clearance_end(self.page, clear, rtl, &self.measurer.work)?
.map_or(extent - reserve, |(page, bottom)| {
if page > self.page {
self.height.max(extent - reserve)
} else {
bottom.max(extent - reserve)
}
});
let y = match letter.and_then(|index| {
letter_atomic(
source,
&cursor.atomics,
&cursor.first_line_atomics,
index,
)
}) {
Some(atomic) if remainder.is_empty() => self
.floats
.last()
.expect("flow has a float context")
.letter_clearance(self.page, y, &self.measurer.work)?
.max(
extent - reserve
+ atomic
.letter
.expect("an initial letter has an extent")
.rise(),
),
_ => y,
};
line_clearance_y = Some(y);
y
};
let Some((line, checkpoint, placement)) = self.fit_float_line(
prepared,
float_position,
(&cursor.metrics, &cursor.first_line_metrics),
[cursor.x, cursor.x + cursor.width],
cleared_y,
)?
else {
break;
};
let next_anchor = consumed_floats
+ trials
.iter()
.filter(|trial| matches!(trial, FloatTrial::Float { .. }))
.count();
if let Some(anchor) = float_anchors.get(next_anchor).filter(|anchor| {
anchor.offset < line.range.end
|| (anchor.offset == line.range.end
&& !source.text()[line.range.clone()]
.ends_with(['\n', '\u{2028}', '\u{2029}']))
}) {
let measured = self.measure_float(
anchor.block(),
cursor.width,
cursor.containing_height,
)?;
let prefix = (line.x_at(source, anchor.offset, style.used_rtl())
- line.x_at(source, line.range.start, style.used_rtl()))
.abs();
let occupied = prefix + if prefix > 0.0 { line.indent } else { 0.0 };
let y = placement.y
+ if measured.size[0] + occupied > placement.width {
line.height
} else {
0.0
};
if y > placement.y && remainder.is_empty() {
self.place_letter_trial(
letter,
(source, &cursor.atomics, &cursor.first_line_atomics),
&line,
placement,
style.used_rtl(),
trials,
);
}
self.place_inline_float(
measured,
anchor,
[cursor.x, cursor.width, y],
&cursor.layers,
)?;
trials.push(FloatTrial::Float {
anchor: next_anchor,
line: remainder.len(),
y,
});
continue;
}
if remainder.is_empty() {
self.place_letter_trial(
letter,
(source, &cursor.atomics, &cursor.first_line_atomics),
&line,
placement,
style.used_rtl(),
trials,
);
}
extent = placement.y + reserve;
cursor.geometry.push_back(placement);
float_position = checkpoint;
line_clearance_y = None;
(line, checkpoint)
} else {
let Some(line) = stream.next() else {
break;
};
(line?, stream.checkpoint())
};
self.measurer.work.spend(line.range.len().max(1))?;
extent += line.height;
overflow |= overflows(extent, self.height);
if !overflow {
available += 1;
}
remainder.push(line);
checkpoints.push(checkpoint);
if overflow && remainder.len() > available.saturating_add(style.widows) {
cursor.candidate_complete = false;
break;
}
}
cursor.anchors =
crate::layout::measure::line_anchors(source, &remainder, cursor.candidate_complete)
.into_iter()
.skip(consumed_anchors)
.collect::<Vec<_>>()
.into_iter()
.peekable();
cursor.line_index = 0;
cursor.positions = checkpoints.into_iter();
cursor.lines = remainder.into_iter();
}
Ok(())
}
pub(super) fn paragraph_fragment(
&mut self,
cursor: Box<ParagraphCursor<'a, 'a>>,
tail: BreakTail,
) -> Result<Option<(Box<ParagraphCursor<'a, 'a>>, BreakRequest)>, LayoutError> {
let mut fragment = self.fit_paragraph_fragment(cursor, tail)?;
for _ in 0..fragment.take {
self.place_fragment_line(&mut fragment)?;
}
self.end_paragraph_fragment(fragment)
}
#[inline(never)]
fn fit_paragraph_fragment(
&mut self,
mut cursor: Box<ParagraphCursor<'a, 'a>>,
tail: BreakTail,
) -> Result<ParagraphFragment<'a>, LayoutError> {
let float_anchors: Vec<_> = cursor
.source
.anchors()
.iter()
.filter(|anchor| anchor.block().style().floating().is_some())
.collect();
let has_inline_floats =
cursor.consumed_floats < float_anchors.len() || cursor.letter.is_some();
let mut snapshot = has_inline_floats.then(|| self.snapshot()).transpose()?;
let saved_layers = has_inline_floats.then(|| cursor.layers.clone());
let mut trials: Vec<FloatTrial> = Vec::new();
let mut request = BreakRequest::default();
let fits = !(cursor.lines.as_slice().is_empty() && cursor.candidate_complete);
let (reserve, closing_reserve) = if fits {
self.measurer.work.spend(1)?;
let reserve = self.continuation_reserve()?;
(reserve, self.closing_reserve(tail, reserve)?)
} else {
(0.0, 0.0)
};
if fits {
self.fit_paragraph_lines(
&mut cursor,
reserve,
(&float_anchors, has_inline_floats),
&mut trials,
)?;
}
let text = self.measurer.text;
let ParagraphCursor {
index,
source,
style,
mut prepared,
positions,
position,
lines,
x,
width,
containing_height,
candidate_complete,
candidate_page,
geometry,
anchors,
atomics,
metrics,
first_line_atomics,
first_line_metrics,
consumed_anchors,
consumed_events,
mut consumed_floats,
line_index,
mut layers,
clamp,
letter,
started,
} = *cursor;
let (take, fragment_trim) = 'fragment: {
if !fits {
break 'fragment (0, [false; 2]);
}
layers.set_containing(InlineContaining {
width,
height: containing_height,
rtl: style.used_rtl(),
});
let remaining = lines.as_slice().len();
let mut height = 0.0;
let mut growth = 0.0;
let mut pending_footnotes = Vec::new();
let mut footnote_events = consumed_events;
let mut kept_footnotes = None;
let mut deferred_line = None;
let mut available = 0;
let fragment_trim = self.fragment_text_trim();
for (index, line) in lines.as_slice().iter().enumerate() {
height = geometry
.get(index)
.map_or(height + line.height, |placement| {
placement.y - self.y + line.height
});
let end_trim = if overflows(self.y + height + reserve + growth, self.height) {
fragment_end_trim(text, style, source, line, fragment_trim)?
} else {
0.0
};
if overflows(self.y + height - end_trim + reserve + growth, self.height) {
break;
}
let footnotes = line_footnotes(source, line, &mut footnote_events);
if let Some(policy) = self.deferred_policy(source, line, &footnotes)? {
kept_footnotes = Some(policy);
deferred_line = Some(index);
break;
}
if !footnotes.is_empty() && self.places_footnotes() {
match self.footnote_growth(&footnotes, &mut pending_footnotes)? {
Some(added)
if !overflows(
self.y + height + reserve + growth + added,
self.height,
) =>
{
growth += added;
}
_ => match self.strictest_policy(&footnotes) {
crate::style::FootnotePolicy::Auto => {
available += 1;
break;
}
policy => {
kept_footnotes = Some(policy);
break;
}
},
}
}
available += 1;
if end_trim > 0.0 {
break;
}
}
let mut take = if self.unbroken > 0 {
remaining
} else {
available.min(remaining)
};
let next_geometry = if take > 0 && take < remaining && style.widows > 1 {
self.next_paragraph_geometry()?
.filter(|(next_width, next_height)| {
*next_width != width
|| (!atomics.is_empty() && *next_height != containing_height)
})
} else {
None
};
if take < remaining {
if take < style.orphans
|| (next_geometry.is_none()
&& remaining < style.orphans.saturating_add(style.widows))
{
take = 0;
} else if next_geometry.is_none() && remaining - take < style.widows {
take = remaining - style.widows;
}
}
if take > 0
&& let Some((next_width, next_height)) = next_geometry
{
let mut next_metrics = metrics.clone();
let mut next_first_line_metrics = first_line_metrics.clone();
let mut next_atomics = atomics.clone();
let mut next_first_line = first_line_atomics.clone();
self.remeasure_inline_blocks(
source,
(&mut next_atomics, &mut next_first_line),
next_width,
next_height,
)?;
crate::layout::inline::paragraph_metrics(source, &next_atomics, &mut next_metrics);
crate::layout::inline::first_line_metrics(
source,
&next_metrics,
&next_first_line,
&mut next_first_line_metrics,
);
if prepared.is_none() {
self.measurer.work.spend(source.text().len().max(1))?;
}
let prepared = prepared.get_or_insert_with(|| {
Rc::new(text.prepare_paragraph(source).clamped(clamp.clone()))
});
while take > 0 {
self.measurer.work.spend(next_metrics.len().max(1))?;
let checkpoint = positions.as_slice()[take - 1];
let mut next_lines = prepared
.lines(checkpoint, next_width, &next_metrics)?
.with_first_line_atomics(&next_first_line_metrics)?;
let mut count = 0;
for line in next_lines.by_ref().take(style.widows) {
self.measurer.work.spend(line?.range.len().max(1))?;
count += 1;
}
if count >= style.widows {
break;
}
take -= 1;
if take < style.orphans {
take = 0;
}
}
}
if self.unbroken == 0
&& candidate_complete
&& take == remaining
&& overflows(self.y + height + growth + closing_reserve, self.height)
{
take = if remaining >= style.orphans.saturating_add(style.widows) {
remaining - style.widows
} else {
0
};
}
if take > 0
&& self.unbroken == 0
&& self.has_flow
&& let Some(atomic) = letter
.and_then(|index| letter_atomic(source, &atomics, &first_line_atomics, index))
&& let Some(first) = geometry.front()
{
let bottom = first.y
+ atomic
.letter
.expect("an initial letter has an extent")
.bottom;
let beside = 1 + geometry
.iter()
.skip(1)
.filter(|line| line.y < bottom)
.count();
if take < beside.min(remaining) || overflows(bottom, self.height) {
take = 0;
}
}
let has_flow = if deferred_line.is_some() {
self.has_page_flow()
} else {
self.has_flow
};
if kept_footnotes == Some(crate::style::FootnotePolicy::Block) && !started && has_flow {
take = 0;
}
if take == 0 && !has_flow {
take = available.min(remaining).max(1);
}
let accepted = trials.partition_point(|trial| trial.line() < take);
if accepted < trials.len() {
self.restore_state(*snapshot.take().expect("inline float trial has a snapshot"));
layers = saved_layers.expect("inline float trial saves its layers");
for trial in &trials[..accepted] {
match *trial {
FloatTrial::Float { anchor, y, .. } => {
let anchor = float_anchors[anchor];
let measured =
self.measure_float(anchor.block(), width, containing_height)?;
self.place_inline_float(measured, anchor, [x, width, y], &layers)?;
}
FloatTrial::Letter { side, margin } => self
.floats
.last_mut()
.expect("flow has a float context")
.insert_letter(self.page, side, margin),
}
}
}
consumed_floats += trials[..accepted]
.iter()
.filter(|trial| matches!(trial, FloatTrial::Float { .. }))
.count();
if deferred_line.is_some_and(|line| take <= line)
&& matches!(self.fragmentainers, Fragmentainers::Columns(_))
{
request.forced = Some(Forced::Page);
}
(take, fragment_trim)
};
Ok(ParagraphFragment {
cursor: Box::new(ParagraphCursor {
index,
source,
style,
prepared,
positions,
position,
lines,
x,
width,
containing_height,
candidate_complete,
candidate_page,
geometry,
anchors,
atomics,
metrics,
first_line_atomics,
first_line_metrics,
consumed_anchors,
consumed_events,
consumed_floats,
line_index,
layers,
clamp,
letter,
started,
}),
take,
request,
float_anchors,
fragment_trim,
})
}
fn place_fragment_line(
&mut self,
fragment: &mut ParagraphFragment<'a>,
) -> Result<(), LayoutError> {
let Some(mut line) = self.start_fragment_line(fragment)? else {
return Ok(());
};
let cursor = &mut *fragment.cursor;
let line_layers = cursor.layers.line(&line.line);
self.inline_content(
&line.line,
line.width,
line.x + line.offset,
(&mut cursor.atomics, &mut cursor.first_line_atomics),
line_layers,
)?;
self.finish_fragment_line(fragment, &mut line)
}
#[inline(never)]
fn start_fragment_line(
&mut self,
fragment: &mut ParagraphFragment<'a>,
) -> Result<Option<Box<FragmentLine>>, LayoutError> {
let text = self.measurer.text;
let fragment_trim = fragment.fragment_trim;
let ParagraphCursor {
source,
style,
positions,
position,
lines,
x,
width,
geometry,
anchors,
consumed_anchors,
consumed_events,
line_index,
layers,
..
} = &mut *fragment.cursor;
let (source, style) = (*source, *style);
let Some(mut line) = lines.next() else {
return Ok(None);
};
self.measurer.work.spend(line.range.len().max(1))?;
if !line.phantom
&& fragment_trim[0]
&& (!source.text_box_trim[0] || line.range.start != 0)
&& !self.has_flow
&& self.y <= FRAGMENTATION_TOLERANCE_PT
{
crate::text::trim_line(text, style, &mut line, [true, false])?;
}
let end_trim = fragment_end_trim(text, style, source, &line, fragment_trim)?;
*position = positions
.next()
.expect("each measured line has its source checkpoint");
let (line_x, line_width) = if let Some(placement) = geometry.pop_front() {
self.y = placement.y;
(placement.x, placement.width)
} else {
(*x, *width)
};
let offset = line.alignment_offset(line_width, style.used_rtl());
while let Some(anchor) = anchors.next_if(|anchor| anchor.line == *line_index) {
*consumed_anchors += 1;
self.line_anchor(&anchor, line_x, line_width, offset, line.height, layers);
}
let footnotes = self.line_events(source, &line, consumed_events);
*line_index += 1;
let baseline = self.top + self.y + line.ascent + self.offset[1];
if !line.phantom {
self.record_baselines(self.page, [Some(baseline); 2]);
}
self.record_overflow(Rect {
x: line_x + offset + self.offset[0],
y: self.top + self.y + self.offset[1],
width: line.width,
height: line.height,
});
self.record_line_box(line.height);
let markers: Vec<_> = self
.boxes
.iter_mut()
.filter_map(|active| {
active
.marker
.take()
.filter(|_| active.visible)
.map(|mut marker| {
marker.fragment.x += self.offset[0] - active.offset[0];
marker
})
})
.collect();
for mut marker in markers {
marker.fragment.baseline = baseline;
self.emit_marker(*marker);
}
Ok(Some(Box::new(FragmentLine {
line,
x: line_x,
width: line_width,
offset,
baseline,
end_trim,
footnotes,
})))
}
#[inline(never)]
fn finish_fragment_line(
&mut self,
fragment: &mut ParagraphFragment<'a>,
line: &mut FragmentLine,
) -> Result<(), LayoutError> {
let ParagraphCursor {
index,
style,
layers,
letter,
started,
..
} = &mut *fragment.cursor;
let FragmentLine {
line,
x: line_x,
width: _,
offset,
baseline,
end_trim,
footnotes,
} = line;
let (line_x, offset, baseline, end_trim) = (*line_x, *offset, *baseline, *end_trim);
let line_layers = layers.line(line);
if !line.phantom {
self.record_baselines(self.page, [Some(baseline); 2]);
}
*letter = None;
self.emit_paragraph_line(
*index,
style,
line,
[line_x + offset + self.offset[0], baseline],
line_layers,
);
self.y += line.height;
*started = true;
self.trailing_line = (end_trim != 0.0).then_some((self.y, end_trim));
if !line.phantom && (line.height > 0.0 || !line.text.is_empty()) {
self.has_flow = true;
self.at_page_start = false;
}
if !footnotes.is_empty() && self.places_footnotes() {
self.place_footnotes(footnotes)?;
}
Ok(())
}
#[inline(never)]
fn end_paragraph_fragment(
&mut self,
fragment: ParagraphFragment<'a>,
) -> Result<Option<(Box<ParagraphCursor<'a, 'a>>, BreakRequest)>, LayoutError> {
let ParagraphFragment {
cursor,
request,
float_anchors,
..
} = fragment;
let ParagraphCursor {
index,
source,
style,
prepared,
positions,
position,
lines,
mut x,
mut width,
mut containing_height,
candidate_complete,
candidate_page,
geometry,
anchors,
atomics,
metrics,
first_line_atomics,
first_line_metrics,
consumed_anchors,
consumed_events,
consumed_floats,
line_index,
layers,
clamp,
letter,
started,
} = *cursor;
let mut trailing_clearance = false;
if lines.as_slice().is_empty() && candidate_complete {
let (clear, rtl) = source.clearance_at(source.text().len());
if let Some((page, bottom)) = self
.floats
.last()
.expect("flow has a float context")
.clearance_end(self.page, clear, rtl, &self.measurer.work)?
{
trailing_clearance =
self.unbroken == 0 && (page > self.page || overflows(bottom, self.height));
self.y = self.y.max(if trailing_clearance {
self.height
} else {
bottom
});
}
}
if !lines.as_slice().is_empty() || !candidate_complete || trailing_clearance {
let cursor = Box::new(ParagraphCursor {
index,
source,
style,
prepared,
positions,
position,
lines,
x,
width,
containing_height,
candidate_complete,
candidate_page,
geometry,
anchors,
atomics,
metrics,
first_line_atomics,
first_line_metrics,
consumed_anchors,
consumed_events,
consumed_floats,
line_index,
layers,
clamp,
letter,
started,
});
return Ok(Some((cursor, request)));
}
if let Some((left, destination_width, height)) = self.paragraph_geometry() {
x = left;
width = destination_width;
containing_height = height;
}
for anchor in &float_anchors[consumed_floats..] {
self.measurer.work.spend(1)?;
let measured = self.measure_float(anchor.block(), width, containing_height)?;
self.place_inline_float(measured, anchor, [x, width, self.y], &layers)?;
}
for event in &source.semantic_events()[consumed_events..] {
self.string_locations.record(self.page, &event.event);
}
self.finish_inline_backgrounds(&layers);
Ok(None)
}
fn line_events(
&mut self,
source: &crate::document::Paragraph,
line: &crate::text::Line,
consumed_events: &mut usize,
) -> Vec<usize> {
let text_start = (!line.phantom)
.then(|| {
source.text()[line.range.clone()]
.char_indices()
.find(|(_, ch)| !crate::document::is_css_whitespace(*ch))
.map(|(offset, _)| line.range.start + offset)
})
.flatten();
let mut footnotes = Vec::new();
for fragment in &line.atomics {
let anchor = source.inline_block(fragment.index);
if let Some(event) = anchor.block().semantic_event() {
self.record_event_line(
event.context.element,
line.height,
text_start.is_some_and(|start| start < anchor.offset),
);
}
}
for event in line_semantic_events(source, line, *consumed_events) {
if text_start.is_some_and(|start| start < event.offset) {
self.string_locations.text(self.page);
}
if event.event.context.pseudo.is_none() {
self.record_event_line(
event.event.context.element,
line.height,
text_start.is_some_and(|start| start < event.offset),
);
}
self.string_locations.record(self.page, &event.event);
footnotes.extend(event.event.footnote);
*consumed_events += 1;
}
if !line.phantom {
self.string_locations.text(self.page);
}
footnotes
}
fn emit_paragraph_line(
&mut self,
index: usize,
style: &crate::style::Style,
line: &mut crate::text::Line,
origin: [f32; 2],
line_layers: &InlineLayers<'a>,
) {
let paragraph = line_layers.paragraph;
let parts = self.split_line(
line_layers,
std::mem::take(&mut line.runs),
&line.decorations,
);
let grouped = parts.len() > 1;
let decorates = |run: &crate::text::GlyphRun, decoration: &DecorationPaint| {
decoration.owner.is_none_or(|owner| {
paragraph.is_within(paragraph.spans()[run.source_span].inline_box, owner)
})
};
for part in parts {
if self.force_hidden || (grouped && part.runs.is_empty() && part.decorations.is_empty())
{
continue;
}
let ink_origin = [
origin[0] + part.layer.offset[0],
origin[1] + part.layer.offset[1],
];
for run in &part.runs {
let style = ¶graph.spans()[run.source_span].style;
self.anchors.text(
crate::layout::anchors::ink_key(style),
self.page,
run,
ink_origin,
part.layer.clip,
crate::layout::writing::Frame::for_style(style),
);
}
for decoration in &part.decorations {
let style = decoration.owner.map_or_else(
|| paragraph.style(),
|owner| ¶graph.boxes()[owner].style,
);
for fill in decoration.fills() {
if let Some(rect) = crate::paint::shape_bounds(&fill.shape) {
self.anchors.ink(
crate::layout::anchors::ink_key(style),
self.page,
Rect {
x: rect.x + ink_origin[0],
y: rect.y + ink_origin[1],
..rect
},
part.layer.clip,
);
}
}
}
self.emit_line(
TextLine {
paragraph: index,
text: line.text.clone(),
x: origin[0],
baseline: origin[1],
width: line.width,
height: line.height,
runs: part.runs,
font_size: style.size,
color: style.color,
},
line.ink_bounds,
&part.decorations,
&part.layer,
&decorates,
);
}
}
pub(super) fn row_text(
&mut self,
mut text: crate::layout::measure::RowText<'a>,
row_top: f32,
) -> Result<(), LayoutError> {
let glyphs = text
.line
.runs
.iter()
.map(|run| run.glyphs().len())
.sum::<usize>();
self.measurer.work.spend(
glyphs
.saturating_add(text.line.text.len())
.saturating_add(text.line.boxes.len())
.saturating_add(text.line.links.len())
.saturating_add(text.line.decorations.len())
.saturating_add(text.source.semantic_events().len())
.max(1),
)?;
self.y = row_top + text.baseline - text.line.ascent;
let mut consumed_events = 0;
let footnotes = self.line_events(text.source, &text.line, &mut consumed_events);
if !footnotes.is_empty() && self.places_footnotes() {
self.place_footnotes(&footnotes)?;
}
let baseline = self.top + row_top + text.baseline + self.offset[1];
self.record_baselines(self.page, [Some(baseline); 2]);
self.record_overflow(Rect {
x: text.x + self.offset[0],
y: self.top + self.y + self.offset[1],
width: text.line.width,
height: text.line.height,
});
self.record_line_box(text.line.height);
let containing = InlineContaining::of(self.containing_geometry());
let mut layers = InlineLayers::new(text.source, containing);
let line_layers = layers.line(&text.line);
self.inline_content(
&text.line,
containing.width,
text.x,
(&mut [], &mut []),
line_layers,
)?;
let index = self.measurer.sources.paragraph(text.source);
self.emit_paragraph_line(
index,
text.source.style(),
&mut text.line,
[text.x + self.offset[0], baseline],
line_layers,
);
self.finish_inline_backgrounds(&layers);
Ok(())
}
fn finish_inline_backgrounds(&mut self, layers: &InlineLayers<'a>) {
for (inline_box, fragments, effects) in layers.painted() {
if inline_box.style.clone_decoration {
continue;
}
assemble_background(
fragments,
&mut self.foreground,
true,
inline_box.style.used_rtl(),
);
for &[node, copy, number] in effects {
let (page, slot) = fragments[number];
if let DisplayItem::Box(assembled) = &self.foreground[page][slot].item {
self.clips[node].paints[copy].1.background_box = assembled.background_box;
}
}
}
}
}
fn line_semantic_events<'p>(
source: &'p crate::document::Paragraph,
line: &crate::text::Line,
consumed: usize,
) -> impl Iterator<Item = &'p crate::document::InlineEvent> {
let end = line.range.end;
let last = end == source.text().len();
source
.semantic_events()
.iter()
.skip(consumed)
.take_while(move |event| event.offset < end || last)
}
fn fragment_end_trim(
text: &crate::text::TextContext<'_>,
style: &crate::style::Style,
source: &crate::document::Paragraph,
line: &crate::text::Line,
fragment_trim: [bool; 2],
) -> Result<f32, LayoutError> {
if line.phantom
|| !fragment_trim[1]
|| (source.text_box_trim[1] && line.range.end == source.text().len())
{
return Ok(0.0);
}
let mut trimmed = line.clone();
crate::text::trim_line(text, style, &mut trimmed, [false, true])?;
Ok(line.height - trimmed.height)
}
fn line_footnotes(
source: &crate::document::Paragraph,
line: &crate::text::Line,
consumed: &mut usize,
) -> Vec<usize> {
let events: Vec<_> = line_semantic_events(source, line, *consumed).collect();
*consumed += events.len();
events
.into_iter()
.filter_map(|event| event.event.footnote)
.collect()
}
type InlineBlocks<'s, 'a> = (
&'s crate::document::Paragraph,
&'s [Option<crate::layout::inline::MeasuredAtomic<'a>>],
&'s [Option<crate::layout::inline::MeasuredAtomic<'a>>],
);
fn letter_atomic<'s, 'a>(
source: &crate::document::Paragraph,
atomics: &'s [Option<crate::layout::inline::MeasuredAtomic<'a>>],
first_line: &'s [Option<crate::layout::inline::MeasuredAtomic<'a>>],
index: usize,
) -> Option<&'s crate::layout::inline::MeasuredAtomic<'a>> {
if crate::layout::inline::has_first_line_box(source, index) {
first_line[index].as_ref()
} else {
atomics[index].as_ref()
}
}