mod transform;
mod transform_maps;
mod transform_math;
use crate::document::DocumentError;
use crate::style::{Clear, Style, TextAlign, WhiteSpaceCollapse};
use std::ops::Range;
use std::sync::Arc;
pub(crate) use transform::{CaseRun, OffsetMap, transform_text};
pub(crate) use transform_maps::narrow_width;
pub(crate) const MAX_INLINE_TEXT_BYTES: usize = 64 * 1024 * 1024;
pub(crate) const OBJECT_REPLACEMENT_CHARACTER: char = '\u{fffc}';
pub(crate) struct GeneratedImage {
pub offset: usize,
pub image: Arc<crate::images::Image>,
}
pub(crate) struct TextSpan {
pub range: Range<usize>,
pub style: Style,
pub inline_box: Option<usize>,
pub atomic: Option<usize>,
pub leader: bool,
source: usize,
single_character_source: bool,
}
pub(crate) struct InlineBox {
pub math: Option<crate::document::mathml::Class>,
pub range: Range<usize>,
pub style: Arc<Style>,
pub decoration: crate::graphics::BoxDecoration,
pub parent: Option<usize>,
pub descendants: usize,
pub continued: [bool; 2],
pub navigation: crate::document::BoxNavigation,
pub canvas_source: bool,
}
impl InlineBox {
fn has_edges(&self) -> bool {
self.style.has_inline_edges(self.continued)
}
}
pub(crate) struct Anchor {
pub offset: usize,
block: crate::document::BlockBox,
pub inline_box: Option<usize>,
}
impl Anchor {
pub(crate) fn block(&self) -> &crate::document::BlockBox {
self.block.standing_for()
}
pub(crate) fn shared(&self) -> bool {
self.block.stands_in()
}
}
pub(crate) struct InlineLink {
pub range: Range<usize>,
pub link: usize,
}
pub(crate) struct Paragraph {
marker_image: Option<crate::graphics::BackgroundImage>,
first_formatted_line: bool,
last_formatted_line: bool,
pub(crate) text_box_trim: [bool; 2],
text: String,
style: Box<Style>,
spans: Vec<TextSpan>,
anchors: Vec<Anchor>,
boxes: Vec<InlineBox>,
atomics: Vec<Anchor>,
annotations: Vec<Anchor>,
rubies: Vec<crate::document::ruby::Ruby>,
annotation_align: Option<crate::style::RubyAlign>,
optional_breaks: Vec<usize>,
clearances: Vec<(usize, Clear, bool)>,
links: Vec<InlineLink>,
events: Vec<crate::document::InlineEvent>,
first_line: Option<Box<Paragraph>>,
first_line_offsets: OffsetMap,
text_limits: TextLimits,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct TextLimits {
pub truncated: bool,
pub untransformed: bool,
}
impl TextLimits {
pub(crate) fn union(self, other: Self) -> Self {
Self {
truncated: self.truncated || other.truncated,
untransformed: self.untransformed || other.untransformed,
}
}
}
impl Paragraph {
pub(crate) fn text_limits(&self) -> TextLimits {
self.first_line
.as_ref()
.map_or(self.text_limits, |variant| {
self.text_limits.union(variant.text_limits)
})
}
pub(super) fn reflow(&mut self) -> Vec<&mut crate::document::BlockBox> {
use crate::style::logical::{self, Flow};
let reflow = |style: &Style| logical::reflowed(style, Flow::of(style).horizontal());
let mut paragraphs = vec![self];
let mut blocks = Vec::new();
while let Some(paragraph) = paragraphs.pop() {
if paragraph.style.used_writing_mode().vertical() {
*paragraph.style = reflow(¶graph.style);
}
for span in &mut paragraph.spans {
if span.style.used_writing_mode().vertical() {
span.style = reflow(&span.style);
}
}
for inline in &mut paragraph.boxes {
let flow = Flow::of(&inline.style);
if flow.writing_mode.vertical() {
inline.decoration =
logical::decoration(&inline.decoration, flow, flow.horizontal());
*Arc::make_mut(&mut inline.style) = reflow(&inline.style);
}
}
blocks.extend(
paragraph
.anchors
.iter_mut()
.chain(&mut paragraph.atomics)
.chain(&mut paragraph.annotations)
.map(|anchor| &mut anchor.block),
);
if let Some(first) = &mut paragraph.first_line {
paragraphs.push(first);
}
}
blocks
}
pub(crate) fn first_line(&self) -> Option<&Self> {
self.first_line.as_deref()
}
pub(crate) fn first_line_offsets(&self) -> &OffsetMap {
&self.first_line_offsets
}
pub(crate) fn set_text_box_trim(&mut self, trim: [bool; 2]) {
self.text_box_trim = trim;
if let Some(variant) = &mut self.first_line {
variant.text_box_trim = trim;
}
}
pub(crate) fn size_initial_letter(&mut self, ratio: f32, edges: [crate::style::TextEdge; 2]) {
self.style.size *= ratio;
self.style.text_box.edges = edges;
for span in &mut self.spans {
span.style.size *= ratio;
}
for inline_box in &mut self.boxes {
Arc::make_mut(&mut inline_box.style).size *= ratio;
}
}
pub(crate) fn set_formatted_lines(&mut self, first: bool, last: bool) {
self.first_formatted_line = first;
self.last_formatted_line = last;
if let Some(variant) = &mut self.first_line {
variant.first_formatted_line = first;
variant.last_formatted_line = last;
}
}
pub(crate) fn first_line_copy(
&self,
root: Style,
lines: Vec<(Style, crate::graphics::BoxDecoration)>,
spans: Vec<Style>,
boxes: Vec<(Style, crate::graphics::BoxDecoration)>,
atomics: Vec<Style>,
) -> Self {
let count = lines.len();
let shift = |inline_box: Option<usize>| {
inline_box.map_or(count.checked_sub(1), |index| Some(index + count))
};
let end = self.text.len();
let descendants = self.boxes.len();
let mut copied: Vec<InlineBox> = lines
.into_iter()
.enumerate()
.map(|(index, (style, decoration))| InlineBox {
math: None,
range: 0..end,
style: style.into(),
decoration,
parent: index.checked_sub(1),
descendants: count - 1 - index + descendants,
continued: [false; 2],
navigation: crate::document::BoxNavigation::default(),
canvas_source: false,
})
.collect();
copied.extend(
self.boxes
.iter()
.zip(boxes)
.map(|(inline_box, (style, decoration))| InlineBox {
math: inline_box.math.clone(),
range: inline_box.range.clone(),
style: style.into(),
decoration,
parent: shift(inline_box.parent),
descendants: inline_box.descendants,
continued: inline_box.continued,
navigation: inline_box.navigation,
canvas_source: inline_box.canvas_source,
}),
);
let mut copy = Self {
annotation_align: self.annotation_align,
marker_image: None,
first_formatted_line: self.first_formatted_line,
last_formatted_line: self.last_formatted_line,
text_box_trim: self.text_box_trim,
text: self.text.clone(),
style: Box::new(root),
spans: self
.spans
.iter()
.zip(spans)
.map(|(span, style)| TextSpan {
range: span.range.clone(),
style,
inline_box: shift(span.inline_box),
atomic: span.atomic,
leader: span.leader,
source: span.source,
single_character_source: span.single_character_source,
})
.collect(),
anchors: Vec::new(),
boxes: copied,
atomics: Vec::new(),
annotations: Vec::new(),
rubies: self
.rubies
.iter()
.map(|ruby| ruby.shifted(count, 0))
.collect(),
optional_breaks: self.optional_breaks.clone(),
clearances: self.clearances.clone(),
links: self
.links
.iter()
.map(|link| InlineLink {
range: link.range.clone(),
link: link.link,
})
.collect(),
events: Vec::new(),
first_line: None,
first_line_offsets: OffsetMap::default(),
text_limits: self.text_limits,
};
let mut styles = atomics.into_iter();
let mut restyled = |anchors: &[Anchor]| -> Vec<Anchor> {
anchors
.iter()
.zip(styles.by_ref())
.map(|(anchor, style)| Anchor {
offset: anchor.offset,
block: crate::document::BlockBox::anonymous(style, Vec::new(), None),
inline_box: shift(anchor.inline_box),
})
.collect()
};
copy.atomics = restyled(&self.atomics);
copy.annotations = restyled(&self.annotations);
copy
}
pub(crate) fn math_children(&self) -> Vec<crate::document::mathml::Class> {
math_children(&self.boxes, &self.atomics, &self.spans, None)
}
pub(crate) fn generated(text: &str, style: &Style) -> Result<Option<Self>, DocumentError> {
let mut collector = InlineCollector::default();
collector.append(text, style);
Ok(collector.finish(style)?.ok())
}
pub(crate) fn styled(
text: String,
style: &Style,
boxes: impl IntoIterator<Item = (Range<usize>, Arc<Style>, Option<usize>)>,
spans: impl IntoIterator<Item = (Range<usize>, Style, Option<usize>)>,
) -> Self {
let boxes: Vec<_> = boxes.into_iter().collect();
let mut descendants = vec![0; boxes.len()];
for (index, (_, _, parent)) in boxes.iter().enumerate().rev() {
if let Some(parent) = *parent {
crate::work::count(crate::work::Work::BoxAncestor, 1);
descendants[parent] += descendants[index] + 1;
}
}
let boxes = boxes
.into_iter()
.zip(descendants)
.map(|((range, style, parent), descendants)| InlineBox {
math: None,
range,
style,
decoration: crate::graphics::BoxDecoration::default(),
parent,
descendants,
continued: [false; 2],
navigation: crate::document::BoxNavigation::default(),
canvas_source: false,
})
.collect();
Paragraph {
annotation_align: None,
marker_image: None,
first_formatted_line: true,
last_formatted_line: true,
text_box_trim: [false; 2],
text,
style: Box::new(style.clone()),
spans: spans
.into_iter()
.enumerate()
.map(|(source, (range, style, inline_box))| TextSpan {
range,
style,
inline_box,
atomic: None,
leader: false,
source,
single_character_source: false,
})
.collect(),
anchors: Vec::new(),
boxes,
atomics: Vec::new(),
annotations: Vec::new(),
rubies: Vec::new(),
optional_breaks: Vec::new(),
clearances: Vec::new(),
links: Vec::new(),
events: Vec::new(),
first_line: None,
first_line_offsets: OffsetMap::default(),
text_limits: TextLimits::default(),
}
}
pub(crate) fn generated_output(
output: &crate::style::GeneratedOutput,
images: &[GeneratedImage],
style: &Style,
) -> Result<Option<Self>, DocumentError> {
let mut collector = InlineCollector::default();
collector.append_generated(output, images, style);
Ok(collector.finish(style)?.ok())
}
pub(crate) fn generated_marker(
output: &crate::style::GeneratedOutput,
images: &[GeneratedImage],
style: &Style,
) -> Result<Option<Self>, DocumentError> {
Self::marker_with(style, |collector, style| {
collector.append_generated(output, images, style);
Ok(())
})
}
fn marker_with(
style: &Style,
fill: impl FnOnce(&mut InlineCollector, &Style) -> Result<(), DocumentError>,
) -> Result<Option<Self>, DocumentError> {
let style = Self::marker_style(style);
let mut collector = InlineCollector::default();
fill(&mut collector, &style)?;
Ok(collector.finish(&style)?.ok().map(|mut paragraph| {
paragraph.first_formatted_line = false;
paragraph.last_formatted_line = false;
paragraph
}))
}
pub(crate) fn image_marker(image: crate::graphics::BackgroundImage, style: &Style) -> Self {
let style = Self::marker_style(style);
let text = String::from(' ');
let span = TextSpan {
range: 0..text.len(),
style: style.clone(),
inline_box: None,
atomic: None,
leader: false,
source: 0,
single_character_source: true,
};
let mut paragraph = Self {
marker_image: Some(image),
annotation_align: None,
first_formatted_line: false,
last_formatted_line: false,
text_box_trim: [false; 2],
text,
style: Box::new(style),
spans: vec![span],
anchors: Vec::new(),
boxes: Vec::new(),
atomics: Vec::new(),
annotations: Vec::new(),
rubies: Vec::new(),
optional_breaks: Vec::new(),
clearances: Vec::new(),
links: Vec::new(),
events: Vec::new(),
first_line: None,
first_line_offsets: OffsetMap::default(),
text_limits: TextLimits::default(),
};
transform::apply(&mut paragraph, false);
paragraph
}
fn marker_style(style: &Style) -> Style {
let mut style = style.clone();
style.align = TextAlign::Start;
style.align_last = None;
style.text_indent = Default::default();
style
}
pub(crate) fn marker_image(&self) -> Option<&crate::graphics::BackgroundImage> {
self.marker_image.as_ref()
}
pub(crate) fn marker_image_size(&self) -> Option<[f32; 2]> {
let area = [self.style.size; 2];
let natural = crate::paint::Source::of(self.marker_image.as_ref()?)
.ok()
.flatten()
.map(|source| source.natural(area))
.unwrap_or_default();
Some(crate::graphics::image_size(
&Default::default(),
natural,
area,
))
}
pub(crate) fn first_formatted_line(&self) -> bool {
self.first_formatted_line
}
pub(crate) fn last_formatted_line(&self) -> bool {
self.last_formatted_line
}
pub(crate) fn text(&self) -> &str {
&self.text
}
pub(crate) fn style(&self) -> &Style {
&self.style
}
pub(crate) fn spans(&self) -> &[TextSpan] {
&self.spans
}
pub(crate) fn anchors(&self) -> &[Anchor] {
&self.anchors
}
pub(crate) fn boxes(&self) -> &[InlineBox] {
&self.boxes
}
pub(crate) fn atomics(&self) -> &[Anchor] {
&self.atomics
}
pub(crate) fn annotations(&self) -> &[Anchor] {
&self.annotations
}
pub(super) fn align_annotation(&mut self, align: crate::style::RubyAlign) {
self.annotation_align = Some(align);
if let Some(first_line) = &mut self.first_line {
first_line.align_annotation(align);
}
}
pub(crate) fn annotation_align(&self) -> Option<crate::style::RubyAlign> {
self.annotation_align
}
pub(crate) fn rubies(&self) -> &[crate::document::ruby::Ruby] {
&self.rubies
}
pub(crate) fn inter_character_base_style(&self, atomic: usize) -> Option<&Style> {
let annotation = atomic.checked_sub(self.atomics.len())?;
for ruby in &self.rubies {
for segment in &ruby.segments {
for level in &segment.levels {
if !level.inter_character {
continue;
}
if let Some(annotation) = level
.annotations
.iter()
.find(|item| item.block == Some(annotation))
{
let base = if self.boxes[ruby.container].style.used_rtl() {
annotation.bases.start
} else {
annotation.bases.end - 1
};
return Some(&self.boxes[segment.bases[base]].style);
}
}
}
}
None
}
pub(crate) fn annotation_box_style(&self, index: usize) -> &Style {
self.rubies
.iter()
.flat_map(|ruby| &ruby.segments)
.flat_map(|segment| &segment.levels)
.flat_map(|level| &level.annotations)
.find(|annotation| annotation.block == Some(index))
.map(|annotation| &*annotation.style)
.expect("each annotation box belongs to a ruby annotation")
}
pub(crate) fn inline_blocks(&self) -> impl Iterator<Item = &Anchor> {
self.atomics.iter().chain(&self.annotations)
}
pub(crate) fn inline_block(&self, index: usize) -> &Anchor {
self.atomics
.get(index)
.unwrap_or_else(|| &self.annotations[index - self.atomics.len()])
}
pub(super) fn annotation_block_mut(&mut self, index: usize) -> &mut crate::document::BlockBox {
&mut self.annotations[index].block
}
pub(super) fn untransformed_copy(&mut self) -> Self {
let mut copy = self.first_line_copy(
(*self.style).clone(),
Vec::new(),
self.spans.iter().map(|span| span.style.clone()).collect(),
self.boxes
.iter()
.map(|inline_box| ((*inline_box.style).clone(), inline_box.decoration.clone()))
.collect(),
self.atomics
.iter()
.chain(&self.annotations)
.map(|anchored| anchored.block.style().clone())
.collect(),
);
for (placeholder, annotation) in copy.annotations.iter_mut().zip(&mut self.annotations) {
if let Some(source) = annotation.block.take_annotation_source() {
placeholder.block.keep_annotation_source(source);
}
}
copy.anchors = self
.anchors
.iter()
.map(|anchor| Anchor {
offset: anchor.offset,
block: crate::document::BlockBox::anonymous(
anchor.block.style().clone(),
Vec::new(),
None,
),
inline_box: anchor.inline_box,
})
.collect();
copy
}
pub(super) fn restyled(
self,
(root, spans, boxes): (
Style,
Vec<Style>,
Vec<(Style, crate::graphics::BoxDecoration)>,
),
contents: &mut Self,
) -> Self {
let mut copy = self.first_line_copy(root, Vec::new(), spans, boxes, Vec::new());
let share = |placeholders: Vec<Anchor>,
anchored: &mut [Anchor],
stand_in: fn(&mut crate::document::BlockBox) -> crate::document::BlockBox| {
placeholders
.into_iter()
.zip(anchored)
.map(|(placeholder, anchor)| Anchor {
block: stand_in(&mut anchor.block),
..placeholder
})
.collect()
};
copy.atomics = share(
self.atomics,
&mut contents.atomics,
crate::document::BlockBox::first_line_stand_in,
);
copy.anchors = share(
self.anchors,
&mut contents.anchors,
crate::document::BlockBox::shared_stand_in,
);
copy.annotations = self.annotations;
transform::apply(&mut copy, false);
copy
}
pub(crate) fn annotation_contents(&self, index: usize) -> Option<&Self> {
contents(&self.annotations[index].block)
}
pub(crate) fn first_line_annotation_contents(&self, index: usize) -> Option<&Self> {
contents(self.annotations[index].block.first_line_box()?)
}
pub(crate) fn measured_blocks(&self) -> Vec<&Anchor> {
let mut blocks: Vec<&Anchor> = self.inline_blocks().collect();
for index in 0..self.annotations.len() {
if let Some(contents) = self.annotation_contents(index) {
blocks.extend(contents.measured_blocks());
}
}
blocks
}
pub(crate) fn annotation_metrics(&self, index: usize) -> Range<usize> {
let count = |index: usize| {
self.annotation_contents(index)
.map_or(0, |contents| contents.measured_blocks().len())
};
let start =
self.atomics.len() + self.annotations.len() + (0..index).map(count).sum::<usize>();
start..start + count(index)
}
pub(crate) fn anchored_blocks_mut(
&mut self,
) -> impl Iterator<Item = &mut crate::document::BlockBox> {
self.anchors
.iter_mut()
.chain(&mut self.atomics)
.chain(&mut self.annotations)
.map(|anchor| &mut anchor.block)
}
pub(crate) fn optional_breaks(&self) -> &[usize] {
&self.optional_breaks
}
pub(crate) fn clearance_at(&self, offset: usize) -> (Clear, bool) {
self.clearances
.binary_search_by_key(&offset, |value| value.0)
.ok()
.map_or((Clear::None, self.style.rtl), |index| {
let (_, clear, rtl) = self.clearances[index];
(clear, rtl)
})
}
pub(crate) fn links(&self) -> &[InlineLink] {
&self.links
}
pub(crate) fn positioned_within(
&self,
inner: Option<usize>,
outer: Option<usize>,
) -> Option<usize> {
std::iter::successors(inner, |&index| self.boxes[index].parent)
.take_while(|&index| Some(index) != outer)
.find(|&index| self.boxes[index].style.position != crate::style::Position::Static)
}
pub(crate) fn is_within(&self, inner: Option<usize>, outer: usize) -> bool {
inner.is_some_and(|inner| (outer..=outer + self.boxes[outer].descendants).contains(&inner))
}
pub(crate) fn semantic_events(&self) -> &[crate::document::InlineEvent] {
&self.events
}
pub(crate) fn into_non_text(self) -> Vec<crate::document::BlockContent> {
non_text(self.anchors, self.events)
}
pub(crate) fn into_text_and_atomics(self) -> (String, Vec<(usize, crate::document::BlockBox)>) {
let atomics = self
.atomics
.into_iter()
.map(|atomic| (atomic.offset, atomic.block))
.collect();
(self.text, atomics)
}
pub(crate) fn leader_at(&self, offset: usize) -> bool {
self.following_span(offset).is_some_and(|span| span.leader)
}
pub(crate) fn style_at(&self, offset: usize) -> &Style {
self.following_span(offset)
.map_or(&self.style, |span| &span.style)
}
pub(crate) fn span_at(&self, offset: usize) -> Option<&TextSpan> {
self.following_span(offset)
.filter(|span| span.range.contains(&offset))
}
fn following_span(&self, offset: usize) -> Option<&TextSpan> {
self.spans.get(self.spans.partition_point(|span| {
crate::work::count(crate::work::Work::SpanProbe, 1);
span.range.end <= offset
}))
}
}
#[derive(Clone, Copy)]
enum Mark {
Anchor(usize),
BoxStart(usize),
BoxEnd(usize),
OptionalBreak(usize),
LinkStart(usize),
LinkEnd(usize),
Event(usize),
}
#[derive(Clone, Copy)]
struct PendingSpace {
style: usize,
source: usize,
single_character_source: bool,
inline_box: Option<usize>,
}
pub(crate) struct OpenContents {
boxes: Vec<ContinuedBox>,
links: Vec<Option<usize>>,
}
struct ContinuedBox {
style: Arc<Style>,
decoration: crate::graphics::BoxDecoration,
navigation: crate::document::BoxNavigation,
canvas_source: bool,
math: Option<crate::document::mathml::Class>,
}
#[derive(Clone, Copy, Default)]
pub(crate) struct ContentMark([usize; 4]);
#[derive(Default)]
pub(crate) struct InlineCollector {
text: String,
spans: Vec<TextSpan>,
styles: Vec<Style>,
pending_space: Option<PendingSpace>,
next_source: usize,
anchors: Vec<Anchor>,
boxes: Vec<InlineBox>,
atomics: Vec<Anchor>,
annotations: Vec<Anchor>,
rubies: Vec<crate::document::ruby::Ruby>,
optional_breaks: Vec<usize>,
clearances: Vec<(usize, Clear, bool)>,
open_box: Option<usize>,
after_space: Vec<Mark>,
links: Vec<InlineLink>,
events: Vec<crate::document::InlineEvent>,
open_links: Vec<Option<usize>>,
marker_end: usize,
sunken_letter_end: Option<usize>,
text_limited: bool,
}
impl InlineCollector {
pub(crate) fn content_mark(&self) -> ContentMark {
ContentMark([
self.events.len(),
self.anchors.len(),
self.atomics.len(),
self.annotations.len(),
])
}
pub(crate) fn content_events_after<'a>(
&'a self,
ContentMark([events_from, anchors_from, atomics_from, annotations_from]): ContentMark,
events: &mut Vec<&'a crate::document::SemanticEvent>,
) -> usize {
let inline = &self.events[events_from..];
let mut visited = inline.len();
events.extend(inline.iter().map(|event| &event.event));
for anchor in self.anchors[anchors_from..]
.iter()
.chain(&self.atomics[atomics_from..])
.chain(&self.annotations[annotations_from..])
{
let (subtree, boxes) = anchor.block.subtree_events();
visited += boxes + subtree.len();
events.extend(subtree);
}
visited
}
pub(crate) fn open_marker(
&mut self,
style: &Style,
navigation: crate::document::BoxNavigation,
) {
self.open_box(
style,
crate::graphics::BoxDecoration::default(),
navigation,
false,
);
}
pub(crate) fn close_marker(&mut self) {
self.close_box();
self.marker_end = self.text.len();
}
pub(crate) fn semantic_event(&mut self, event: crate::document::SemanticEvent) {
let index = self.events.len();
self.events.push(crate::document::InlineEvent {
offset: self.text.len(),
event,
anchors_before: self.anchors.len(),
});
if self.pending_space.is_some() {
self.after_space.push(Mark::Event(index));
}
}
fn style_index(&mut self, style: &Style) -> usize {
if self
.styles
.last()
.is_none_or(|last| !last.same_text_style(style) || !last.origin.same(&style.origin))
{
self.styles.push(style.clone());
}
self.styles.len() - 1
}
fn next_source(&mut self) -> usize {
self.next_source += 1;
self.next_source - 1
}
pub(crate) fn append_generated(
&mut self,
output: &crate::style::GeneratedOutput,
images: &[GeneratedImage],
style: &Style,
) {
self.append_generated_from(output, images, 0, style);
}
pub(crate) fn append_generated_from(
&mut self,
output: &crate::style::GeneratedOutput,
images: &[GeneratedImage],
start: usize,
style: &Style,
) {
let text = output.text();
let mut from = start;
let mut leaders = output.leaders().iter().peekable();
let mut images = images.iter().peekable();
loop {
let leader = leaders.peek().map(|range| range.start);
let image_next = match (leader, images.peek().map(|image| image.offset)) {
(None, None) => break,
(Some(leader), Some(image)) => image <= leader,
(Some(_), None) => false,
(None, Some(_)) => true,
};
if image_next {
let image = images.next().expect("an image is next");
self.append(&text[from..image.offset], style);
self.atomic(
crate::document::BlockBox::anonymous_replaced(
style.anonymous(crate::style::Display::Inline),
image.image.clone(),
None,
),
style,
);
from = image.offset;
} else {
let range = leaders.next().expect("a leader is next");
self.append(&text[from..range.start], style);
self.append_inner(&text[range.clone()], style, true);
from = range.end;
}
}
self.append(&text[from..], style);
}
pub(crate) fn at_line_start(&self) -> bool {
self.text.len() == self.marker_end
}
pub(crate) fn at_first_child(&self) -> bool {
let mut open = 0;
let mut inner = self.open_box;
while let Some(index) = inner {
if self.boxes[index].continued[0] {
return false;
}
open += 1;
inner = self.boxes[index].parent;
}
self.text.is_empty() && self.atomics.is_empty() && open == self.boxes.len()
}
pub(crate) fn open_style(&self) -> Option<&Style> {
self.open_box.map(|index| &*self.boxes[index].style)
}
pub(crate) fn innermost_box(&self) -> Option<usize> {
self.open_box
}
pub(crate) fn push_annotation(&mut self, block: crate::document::BlockBox) -> usize {
self.annotations.push(Anchor {
offset: self.text.len(),
block,
inline_box: self.open_box,
});
self.annotations.len() - 1
}
pub(crate) fn push_ruby(&mut self, ruby: crate::document::ruby::Ruby) {
self.rubies.push(ruby);
}
pub(crate) fn initial_letter(
&mut self,
block: crate::document::BlockBox,
style: &Style,
marker: bool,
) {
let sunken = block
.style()
.initial_letter
.is_some_and(|initial| initial.sink > 1);
let start = self.text.len();
let ancestors = std::mem::take(&mut self.open_box);
self.atomic(block, style);
self.open_box = ancestors;
for inline_box in &mut self.boxes {
if inline_box.range.start == start {
inline_box.range.start = self.text.len();
}
}
if marker {
self.marker_end = self.text.len();
}
if sunken {
self.sunken_letter_end = Some(self.text.len());
}
}
pub(crate) fn restyle(
&mut self,
mut restyle: impl FnMut(&Style) -> Result<Style, DocumentError>,
mut decorate: impl FnMut(&Style) -> crate::graphics::BoxDecoration,
) -> Result<(), DocumentError> {
for style in &mut self.styles {
*style = restyle(style)?;
}
for span in &mut self.spans {
span.style = restyle(&span.style)?;
}
for inline_box in &mut self.boxes {
inline_box.style = restyle(&inline_box.style)?.into();
inline_box.decoration = decorate(&inline_box.style);
}
Ok(())
}
pub(crate) fn append(&mut self, text: &str, style: &Style) {
self.append_inner(text, style, false);
}
fn append_inner(&mut self, text: &str, style: &Style, leader: bool) {
if leader {
self.emit_pending_space();
}
let first_span = self.spans.len();
let index = self.style_index(style);
let source = self.next_source();
let inline_box = self.open_box;
let single_character_source = text.chars().nth(1).is_none();
for ch in text.chars() {
if ch == '\n' && style.white_space.preserves_breaks() {
self.drop_pending_space();
self.push('\n', index, source, single_character_source, inline_box);
} else if collapses_character(ch, style.white_space.collapse) {
if self.pending_space.is_none()
&& (leader
|| (self.text.len() != self.marker_end
&& self.sunken_letter_end != Some(self.text.len())
&& !self.text.ends_with('\n')))
{
self.pending_space = Some(PendingSpace {
style: index,
source,
single_character_source,
inline_box,
});
}
} else if style.white_space.collapse.converts_to_spaces() && matches!(ch, '\n' | '\t') {
self.emit_pending_space();
self.push(' ', index, source, single_character_source, inline_box);
} else {
self.emit_pending_space();
self.push(ch, index, source, single_character_source, inline_box);
}
}
if leader {
self.emit_pending_space();
for span in &mut self.spans[first_span..] {
span.leader = true;
}
}
}
fn emit_pending_space(&mut self) {
if let Some(space) = self.pending_space.take() {
self.push(
' ',
space.style,
space.source,
space.single_character_source,
space.inline_box,
);
let end = self.text.len();
for mark in std::mem::take(&mut self.after_space) {
match mark {
Mark::Event(index) => self.events[index].offset = end,
Mark::Anchor(index) => self.anchors[index].offset = end,
Mark::BoxStart(index) => self.boxes[index].range.start = end,
Mark::BoxEnd(index) => self.boxes[index].range.end = end,
Mark::OptionalBreak(index) => self.optional_breaks[index] = end,
Mark::LinkStart(index) => self.links[index].range.start = end,
Mark::LinkEnd(index) => self.links[index].range.end = end,
}
}
}
}
pub(crate) fn drop_pending_space(&mut self) {
self.pending_space = None;
self.after_space.clear();
}
pub(crate) fn anchor_count(&self) -> usize {
self.anchors.len()
}
pub(crate) fn take_anchors_after(&mut self, count: usize) -> Vec<crate::document::BlockBox> {
self.after_space
.retain(|mark| !matches!(mark, Mark::Anchor(index) if *index >= count));
self.anchors
.split_off(count)
.into_iter()
.map(|anchor| anchor.block)
.collect()
}
pub(crate) fn extend(&mut self, other: Self) {
debug_assert!(
other.open_box.is_none() && other.open_links.is_empty(),
"a collector is appended after its boxes close"
);
if other.text.is_empty()
&& other.boxes.is_empty()
&& other.anchors.is_empty()
&& other.annotations.is_empty()
&& other.events.is_empty()
{
return;
}
self.emit_pending_space();
let offset = self.text.len();
if offset
.checked_add(other.text.len())
.is_none_or(|length| length > MAX_INLINE_TEXT_BYTES)
{
self.text_limited = true;
return;
}
self.text_limited |= other.text_limited;
let parent = self.open_box;
let boxes = self.boxes.len();
let anchors = self.anchors.len();
let atomics = self.atomics.len();
let annotations = self.annotations.len();
let breaks = self.optional_breaks.len();
let links = self.links.len();
let events = self.events.len();
let styles = self.styles.len();
let sources = self.next_source;
let inline_box = |inner: Option<usize>| inner.map_or(parent, |inner| Some(inner + boxes));
let shift = |range: Range<usize>| range.start + offset..range.end + offset;
self.text.push_str(&other.text);
self.spans
.extend(other.spans.into_iter().map(|span| TextSpan {
range: shift(span.range),
inline_box: inline_box(span.inline_box),
atomic: span.atomic.map(|atomic| atomic + atomics),
source: span.source + sources,
..span
}));
self.styles.extend(other.styles);
self.pending_space = other.pending_space.map(|space| PendingSpace {
style: space.style + styles,
source: space.source + sources,
single_character_source: space.single_character_source,
inline_box: inline_box(space.inline_box),
});
self.after_space
.extend(other.after_space.into_iter().map(|mark| match mark {
Mark::Anchor(index) => Mark::Anchor(index + anchors),
Mark::BoxStart(index) => Mark::BoxStart(index + boxes),
Mark::BoxEnd(index) => Mark::BoxEnd(index + boxes),
Mark::OptionalBreak(index) => Mark::OptionalBreak(index + breaks),
Mark::LinkStart(index) => Mark::LinkStart(index + links),
Mark::LinkEnd(index) => Mark::LinkEnd(index + links),
Mark::Event(index) => Mark::Event(index + events),
}));
self.next_source += other.next_source;
let anchor = |anchor: Anchor| Anchor {
offset: anchor.offset + offset,
inline_box: inline_box(anchor.inline_box),
block: anchor.block,
};
self.anchors.extend(other.anchors.into_iter().map(anchor));
self.atomics.extend(other.atomics.into_iter().map(anchor));
self.annotations
.extend(other.annotations.into_iter().map(anchor));
self.rubies.extend(
other
.rubies
.iter()
.map(|ruby| ruby.shifted(boxes, annotations)),
);
self.boxes
.extend(other.boxes.into_iter().map(|inner| InlineBox {
range: shift(inner.range),
parent: inline_box(inner.parent),
..inner
}));
self.optional_breaks
.extend(other.optional_breaks.into_iter().map(|at| at + offset));
self.clearances.extend(
other
.clearances
.into_iter()
.map(|(at, clear, rtl)| (at + offset, clear, rtl)),
);
self.links
.extend(other.links.into_iter().map(|link| InlineLink {
range: shift(link.range),
link: link.link,
}));
self.events.extend(
other
.events
.into_iter()
.map(|event| crate::document::InlineEvent {
offset: event.offset + offset,
anchors_before: event.anchors_before + anchors,
event: event.event,
}),
);
}
fn mark(&mut self, mark: Mark) {
if self.pending_space.is_some() {
self.after_space.push(mark);
}
}
pub(crate) fn anchor(&mut self, block: crate::document::BlockBox) {
self.mark(Mark::Anchor(self.anchors.len()));
self.anchors.push(Anchor {
offset: self.text.len(),
block,
inline_box: self.open_box,
});
}
pub(crate) fn open_box(
&mut self,
style: &Style,
decoration: crate::graphics::BoxDecoration,
navigation: crate::document::BoxNavigation,
canvas_source: bool,
) {
self.open_continued(
Arc::new(style.clone()),
decoration,
navigation,
false,
canvas_source,
);
}
fn open_continued(
&mut self,
style: Arc<Style>,
decoration: crate::graphics::BoxDecoration,
navigation: crate::document::BoxNavigation,
continued: bool,
canvas_source: bool,
) {
let index = self.boxes.len();
self.mark(Mark::BoxStart(index));
self.boxes.push(InlineBox {
math: None,
range: self.text.len()..self.text.len(),
style,
decoration,
parent: self.open_box,
descendants: 0,
continued: [continued, false],
navigation,
canvas_source,
});
self.open_box = Some(index);
}
pub(super) fn prepare_math_inline(&mut self, element: crate::dom::Element<'_>, style: &Style) {
if element.namespace() != crate::dom::MATHML_NAMESPACE {
return;
}
let Some(index) = self.open_box else {
return;
};
let children = math_children(&self.boxes, &self.atomics, &self.spans, Some(index));
self.boxes[index].math = crate::document::mathml::inline_class(element, style, children);
}
pub(crate) fn close_box(&mut self) {
let index = self
.open_box
.expect("inline boxes close in the order they were opened");
self.mark(Mark::BoxEnd(index));
let count = self.boxes.len();
let inline_box = &mut self.boxes[index];
inline_box.range.end = self.text.len();
inline_box.descendants = count - index - 1;
self.open_box = inline_box.parent;
}
pub(crate) fn open_contents(&mut self, link: Option<usize>) {
let index = link.map(|link| {
let index = self.links.len();
self.mark(Mark::LinkStart(index));
self.links.push(InlineLink {
range: self.text.len()..self.text.len(),
link,
});
index
});
self.open_links.push(index);
}
pub(crate) fn close_contents(&mut self) {
if let Some(index) = self
.open_links
.pop()
.expect("contents scopes close in tree order")
{
self.mark(Mark::LinkEnd(index));
self.links[index].range.end = self.text.len();
}
}
pub(crate) fn split(&mut self) -> Self {
let open = self.close_open();
let mut next = Self {
next_source: self.next_source,
..Self::default()
};
next.reopen(open);
std::mem::replace(self, next)
}
pub(crate) fn close_open(&mut self) -> OpenContents {
let links: Vec<_> = self
.open_links
.iter()
.map(|index| index.map(|index| self.links[index].link))
.collect();
for _ in &links {
self.close_contents();
}
let mut boxes = Vec::new();
let mut inner = self.open_box;
while let Some(index) = inner {
let inline_box = &mut self.boxes[index];
boxes.push(ContinuedBox {
style: inline_box.style.clone(),
decoration: inline_box.decoration.clone(),
navigation: inline_box.navigation,
canvas_source: inline_box.canvas_source,
math: inline_box.math.clone(),
});
inline_box.continued[1] = true;
inner = inline_box.parent;
}
for _ in &boxes {
self.close_box();
}
boxes.reverse();
OpenContents { boxes, links }
}
pub(crate) fn reopen(&mut self, open: OpenContents) {
for continued in open.boxes {
self.open_continued(
continued.style,
continued.decoration,
continued.navigation,
true,
continued.canvas_source,
);
self.boxes
.last_mut()
.expect("a continued box was opened")
.math = continued.math;
}
for link in open.links {
self.open_contents(link);
}
}
pub(crate) fn continue_box(
&mut self,
style: &Style,
decoration: crate::graphics::BoxDecoration,
navigation: crate::document::BoxNavigation,
) {
self.open_continued(Arc::new(style.clone()), decoration, navigation, true, false);
}
pub(crate) fn atomic(&mut self, block: crate::document::BlockBox, style: &Style) {
let collapses_spaces = block.is_unadorned_image_fallback()
&& block.children().is_empty()
&& [&block.style().min_width, &block.style().min_height]
.into_iter()
.all(|size| *size == crate::style::Size::Auto || size.is_zero())
&& block.style().initial_letter.is_none();
if !collapses_spaces {
self.emit_pending_space();
}
let index = self.style_index(style);
let source = self.next_source();
let offset = self.text.len();
self.push(
OBJECT_REPLACEMENT_CHARACTER,
index,
source,
false,
self.open_box,
);
let span = self
.spans
.last_mut()
.expect("the placeholder was just pushed");
span.atomic = Some(self.atomics.len());
self.atomics.push(Anchor {
offset,
block,
inline_box: self.open_box,
});
}
pub(crate) fn open_boxes(&self) -> Vec<Arc<Style>> {
let mut open: Vec<_> =
std::iter::successors(self.open_box, |&index| self.boxes[index].parent)
.map(|index| Arc::clone(&self.boxes[index].style))
.collect();
open.reverse();
open
}
pub(crate) fn inside_inline_box(&self) -> bool {
self.open_box.is_some()
}
pub(crate) fn trailing_atomic(&mut self) -> Option<&mut crate::document::BlockBox> {
let (open_box, end) = (self.open_box, self.text.len());
self.atomics
.last_mut()
.filter(|anchor| {
anchor.inline_box == open_box
&& anchor.offset + OBJECT_REPLACEMENT_CHARACTER.len_utf8() == end
})
.map(|anchor| &mut anchor.block)
}
pub(crate) fn is_between_blocks(&self) -> bool {
self.text.is_empty() && self.open_box.is_none()
}
pub(crate) fn line_break(&mut self, style: &Style) {
self.drop_pending_space();
let index = self.style_index(style);
let source = self.next_source();
self.push('\n', index, source, false, self.open_box);
if style.clear != Clear::None {
self.clearances
.push((self.text.len(), style.clear, style.rtl));
}
}
pub(crate) fn optional_break(&mut self, style: &Style) {
if style.white_space.wraps() {
self.mark(Mark::OptionalBreak(self.optional_breaks.len()));
self.optional_breaks.push(self.text.len());
}
}
fn push(
&mut self,
ch: char,
index: usize,
source: usize,
single_character_source: bool,
inline_box: Option<usize>,
) {
if self
.text
.len()
.checked_add(ch.len_utf8())
.is_none_or(|length| length > MAX_INLINE_TEXT_BYTES)
{
self.text_limited = true;
return;
}
let style = &self.styles[index];
let start = self.text.len();
self.text.push(ch);
if let Some(last) = self.spans.last_mut()
&& last.source == source
&& last.style.same_text_style(style)
{
last.range.end = self.text.len();
} else {
self.spans.push(TextSpan {
range: start..self.text.len(),
style: style.clone(),
inline_box,
atomic: None,
leader: false,
source,
single_character_source,
});
}
}
pub(crate) fn finish(
self,
style: &Style,
) -> Result<Result<Paragraph, Vec<crate::document::BlockContent>>, DocumentError> {
self.finish_with_first_line(style, |_| Ok(None))
}
pub(crate) fn finish_with_first_line(
self,
style: &Style,
first_line: impl FnOnce(&mut Paragraph) -> Result<Option<Paragraph>, DocumentError>,
) -> Result<Result<Paragraph, Vec<crate::document::BlockContent>>, DocumentError> {
if ((self.text.is_empty() && self.annotations.is_empty())
|| (self.spans.iter().any(|span| span.leader)
&& self
.spans
.iter()
.all(|span| span.leader || self.text[span.range.clone()].trim().is_empty())))
&& !self.boxes.iter().any(InlineBox::has_edges)
&& !self
.anchors
.iter()
.any(|anchor| anchor.inline_box.is_some())
{
return Ok(Err(non_text(self.anchors, self.events)));
}
let mut paragraph = Paragraph {
annotation_align: None,
marker_image: None,
first_formatted_line: true,
last_formatted_line: true,
text_box_trim: [false; 2],
text: self.text,
style: Box::new(style.clone()),
spans: self.spans,
anchors: self.anchors,
boxes: self.boxes,
atomics: self.atomics,
annotations: self.annotations,
rubies: self.rubies,
optional_breaks: self.optional_breaks,
clearances: self.clearances,
links: self.links,
events: self.events,
first_line: None,
first_line_offsets: OffsetMap::default(),
text_limits: TextLimits {
truncated: self.text_limited,
untransformed: false,
},
};
let variant = first_line(&mut paragraph)?;
for annotation in &mut paragraph.annotations {
annotation.block.take_annotation_source();
}
let units = transform::apply(&mut paragraph, variant.is_some());
if let Some(mut variant) = variant {
let copy = transform::apply(&mut variant, true);
paragraph.first_line_offsets =
OffsetMap::between([©, &units], [&variant.text, ¶graph.text]);
paragraph.first_line = Some(Box::new(variant));
}
Ok(Ok(paragraph))
}
}
fn non_text(
anchors: Vec<Anchor>,
events: Vec<crate::document::InlineEvent>,
) -> Vec<crate::document::BlockContent> {
let mut output = Vec::new();
let mut events = events.into_iter().peekable();
for (index, anchor) in anchors.into_iter().enumerate() {
let pending: Vec<_> =
std::iter::from_fn(|| events.next_if(|event| event.anchors_before <= index))
.map(|event| event.event)
.collect();
if !pending.is_empty() {
output.push(crate::document::BlockContent::Events(pending));
}
output.push(crate::document::BlockContent::Positioned(anchor.block));
}
let remaining: Vec<_> = events.map(|event| event.event).collect();
if !remaining.is_empty() {
output.push(crate::document::BlockContent::Events(remaining));
}
output
}
pub(crate) fn is_css_whitespace(ch: char) -> bool {
matches!(ch, ' ' | '\t' | '\r' | '\n' | '\u{c}')
}
pub(crate) fn collapses_character(ch: char, collapse: WhiteSpaceCollapse) -> bool {
collapse.collapses_spaces()
&& is_css_whitespace(ch)
&& !(ch == '\n' && collapse.preserves_breaks())
}
fn math_children(
boxes: &[InlineBox],
atomics: &[Anchor],
spans: &[TextSpan],
parent: Option<usize>,
) -> Vec<crate::document::mathml::Class> {
use crate::document::mathml::{Class, block_class};
let mut children: Vec<_> = boxes
.iter()
.filter(|child| child.parent == parent)
.map(|child| (child.range.start, child.math.clone().unwrap_or_default()))
.collect();
children.extend(
atomics
.iter()
.filter(|child| child.inline_box == parent)
.map(|child| (child.offset, block_class(&child.block))),
);
children.extend(
spans
.iter()
.filter(|span| {
span.inline_box == parent && span.atomic.is_none() && !span.range.is_empty()
})
.map(|span| {
(
span.range.start,
Class {
space_like: true,
operator: None,
},
)
}),
);
children.sort_by_key(|(offset, _)| *offset);
children.into_iter().map(|(_, class)| class).collect()
}
fn contents(block: &crate::document::BlockBox) -> Option<&Paragraph> {
match block.children().first() {
Some(crate::document::BlockContent::Inline(contents)) => Some(contents),
_ => None,
}
}