use std::rc::Rc;
use super::*;
use crate::text::{
CssTextScalar, SegmentBreakContext, character_is_currency_symbol, classify_css_text_scalar,
segment_break_is_removable,
};
use crate::units::glyph_baseline_displacement_pt;
pub(in crate::layout) fn push_inline_words_for_style(
text: &str,
style: &ComputedStyle,
link_target: Option<String>,
baseline_shift: f32,
visual_offset: InlineVisualOffset,
output: &mut Vec<InlineItem>,
) {
let used_style = css::LayoutStyle::from_computed(style).into_zoomed();
let style = &used_style;
let normalized_style;
let style = if anonymous_inline_content_needs_normalized_style(style) {
normalized_style = normalized_anonymous_inline_content_style(style);
&normalized_style
} else {
style
};
push_inline_text_run(
text,
style,
link_target,
baseline_shift,
visual_offset,
output,
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::css::ContentLanguage;
fn word_styles(items: &[InlineItem]) -> Vec<InlineStyle> {
items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(Rc::clone(&word.style)),
_ => None,
})
.collect()
}
#[test]
fn whitespace_normalization_reuses_inline_word_style_handles() {
let style = ComputedStyle::initial();
let mut items = Vec::new();
push_inline_text_run(
"A\tB",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let styles = word_styles(&items);
assert_eq!(styles.len(), 3);
assert!(Rc::ptr_eq(&styles[0], &styles[1]));
assert!(Rc::ptr_eq(&styles[0], &styles[2]));
}
#[test]
fn equal_nested_decoration_values_retain_distinct_origins() {
let mut ancestor_style = ComputedStyle::initial();
ancestor_style.text_decoration.underline = true;
ancestor_style.rebuild_own_text_decoration_origin();
let ancestor_layer = ancestor_style
.text_decoration_origins
.effective_layers_vec();
let mut child_style = ComputedStyle::initial();
child_style.text_decoration.underline = true;
child_style.rebuild_own_text_decoration_origin();
let chain = propagated_decoration_layers_for_child(&ancestor_layer, &child_style);
assert_eq!(chain.len(), 2);
assert!(!std::rc::Rc::ptr_eq(
&chain[0].origin_style,
&chain[1].origin_style,
));
}
#[test]
fn propagation_context_carries_in_flow_layers_and_stops_at_boundaries() {
let mut ancestor_style = ComputedStyle::initial();
ancestor_style.text_decoration.underline = true;
ancestor_style.rebuild_own_text_decoration_origin();
let context = TextDecorationPropagationContext::from_style(&ancestor_style);
let in_flow_style = ComputedStyle::initial();
let propagated = context.used_child_style(&in_flow_style);
let propagated_layers = propagated.text_decoration_origins.effective_layers_vec();
let ancestor_layers = ancestor_style
.text_decoration_origins
.effective_layers_vec();
assert_eq!(propagated_layers.len(), 1);
assert!(std::rc::Rc::ptr_eq(
&propagated_layers[0].origin_style,
&ancestor_layers[0].origin_style,
));
let mut nested_style = ComputedStyle::initial();
nested_style.text_decoration.underline = true;
nested_style.rebuild_own_text_decoration_origin();
let nested = context.used_child_style(&nested_style);
let nested_layers = nested.text_decoration_origins.effective_layers_vec();
let nested_own_origin = std::rc::Rc::clone(
&nested_style
.text_decoration_origins
.own_layer()
.unwrap()
.origin_style,
);
assert_eq!(nested_layers.len(), 2);
assert!(std::rc::Rc::ptr_eq(
&nested_layers[0].origin_style,
&ancestor_layers[0].origin_style,
));
assert!(std::rc::Rc::ptr_eq(
&nested_layers[1].origin_style,
&nested_own_origin,
));
let mut absolute = ComputedStyle::initial();
absolute.position = Position::Absolute;
let mut floated = ComputedStyle::initial();
floated.float = Float::Left;
let mut atomic = ComputedStyle::initial();
atomic.display = Display::INLINE_BLOCK;
for boundary in [&mut absolute, &mut floated, &mut atomic] {
boundary.text_decoration.underline = true;
boundary.rebuild_own_text_decoration_origin();
let used = context.used_child_style(boundary);
assert_eq!(used.text_decoration_origins.effective_layers().count(), 1);
}
}
#[test]
fn whitespace_normalization_keeps_slice_edges_on_source_boundary_words() {
let style = ComputedStyle::initial();
let edge = |logical_edge, physical_side| {
InlineItem::Atom(Box::new(InlineAtom::new(
InlineAtomContent::InlineEdge(InlineEdgeRole::BoxEdge(InlineBoxEdgeFragment {
logical_edge,
physical_side,
positioning_containing_block_id: None,
advance: 0.0,
paint_extent: 0.0,
})),
style.clone(),
None,
InlineSize::new(0.0, style.line_height),
0.0,
0.0,
None,
None,
)))
};
let mut items = vec![edge(InlineLogicalEdge::Start, PhysicalSide::Left)];
push_inline_text_run(
"target element",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
let Some(InlineItem::Word(word)) = items.last_mut() else {
panic!("the source text should produce one inline word")
};
word.hanging_edges = InlineHangingEdges {
blocks_start: true,
blocks_end: true,
};
items.push(edge(InlineLogicalEdge::End, PhysicalSide::Right));
normalize_inline_whitespace_items(&mut items);
let words = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some((word.text.as_str(), word.hanging_edges)),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(
words,
[
(
"target",
InlineHangingEdges {
blocks_start: true,
blocks_end: false,
},
),
(" ", InlineHangingEdges::default()),
(
"element",
InlineHangingEdges {
blocks_start: false,
blocks_end: true,
},
),
]
);
}
#[test]
fn inline_word_style_mutation_is_copy_on_write() {
let mut style = ComputedStyle::initial();
style.font_size = 12.0;
let shared_style = inline_style(&style);
let mut first = InlineWord {
text: "A".to_string(),
style: Rc::clone(&shared_style),
baseline_shift: 0.0,
visual_offset: InlineVisualOffset::zero(),
link_target: None,
mergeable: true,
source: InlineTextSource::Normal,
hanging_edges: InlineHangingEdges::default(),
excluded_positioning_geometry_source: None,
ancestor_inline_decorations: Vec::new().into(),
};
let second = InlineWord {
text: "B".to_string(),
style: shared_style,
baseline_shift: 0.0,
visual_offset: InlineVisualOffset::zero(),
link_target: None,
mergeable: true,
source: InlineTextSource::Normal,
hanging_edges: InlineHangingEdges::default(),
excluded_positioning_geometry_source: None,
ancestor_inline_decorations: Vec::new().into(),
};
Rc::make_mut(&mut first.style).font_size = 20.0;
assert_eq!(first.style.font_size, 20.0);
assert_eq!(second.style.font_size, 12.0);
assert!(!Rc::ptr_eq(&first.style, &second.style));
}
#[test]
fn preserved_and_generated_segment_breaks_keep_distinct_origins() {
let mut preserved_style = ComputedStyle::initial();
preserved_style.white_space = WhiteSpace::PreWrap;
let mut preserved = Vec::new();
push_inline_text_run(
"A\nB",
&preserved_style,
None,
0.0,
InlineVisualOffset::zero(),
&mut preserved,
);
normalize_inline_whitespace_items(&mut preserved);
assert!(matches!(
preserved.get(1),
Some(InlineItem::Break(InlineBreak {
origin: InlineBreakOrigin::PreservedSegment,
..
}))
));
let mut generated = Vec::new();
push_generated_inline_words_for_style(
"A\nB",
&preserved_style,
None,
0.0,
InlineVisualOffset::zero(),
&mut generated,
);
normalize_inline_whitespace_items(&mut generated);
assert!(matches!(
generated.get(1),
Some(InlineItem::Break(InlineBreak {
origin: InlineBreakOrigin::Explicit,
..
}))
));
}
#[test]
fn collapsed_space_keeps_wrap_ownership_from_a_normal_descendant() {
let mut nowrap = ComputedStyle::initial();
nowrap.white_space = WhiteSpace::NoWrap;
let normal = ComputedStyle::initial();
let mut items = Vec::new();
push_inline_text_run(
"12345 ",
&nowrap,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
push_inline_text_run(
" ",
&normal,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let space = items
.iter()
.find_map(|item| match item {
InlineItem::Word(word) if word.text == " " => Some(word),
_ => None,
})
.expect("collapsed separator should remain in the stream");
assert!(space.style.allows_soft_wrap());
}
#[test]
fn forced_break_keeps_preceding_collapsed_source_space_for_phase_two() {
let style = ComputedStyle::initial();
let mut items = Vec::new();
push_inline_text_run(
"A ",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
items.push(InlineItem::Break(InlineBreak {
clear: Clear::None,
origin: InlineBreakOrigin::Explicit,
}));
normalize_inline_whitespace_items(&mut items);
assert!(matches!(
items.as_slice(),
[InlineItem::Word(first), InlineItem::Word(space), InlineItem::Break(_)]
if first.text == "A" && space.text == " "
));
}
#[test]
fn word_space_transform_keeps_explicit_separator_distinct_from_authored_space() {
let mut style = ComputedStyle::initial();
style.word_space_transform = css::WordSpaceTransform {
replacement: Some(css::WordSpaceReplacement::Space),
auto_phrase: false,
};
let mut items = Vec::new();
push_inline_text_run(
"a\u{200b} b",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let text = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(text, "a b");
assert!(items.iter().any(|item| {
matches!(
item,
InlineItem::Word(word)
if word.text == " "
&& word.source
== InlineTextSource::WordSpaceTransform(
ExplicitWordSeparatorSource::AuthoredZeroWidthSpace
)
)
}));
}
#[test]
fn word_space_transform_marks_generated_wbr_without_source_text() {
let mut style = ComputedStyle::initial();
style.word_space_transform = css::WordSpaceTransform {
replacement: Some(css::WordSpaceReplacement::IdeographicSpace),
auto_phrase: false,
};
let mut items = Vec::new();
push_generated_inline_words_for_style_with_source(
"a\u{200b}b",
&style,
None,
0.0,
InlineVisualOffset::zero(),
InlineTextSource::GeneratedWbr,
&mut items,
);
normalize_inline_whitespace_items(&mut items);
assert!(items.iter().any(|item| {
matches!(
item,
InlineItem::Word(word)
if word.text == "\u{3000}"
&& word.source
== InlineTextSource::WordSpaceTransform(
ExplicitWordSeparatorSource::HtmlWbr
)
)
}));
}
#[test]
fn word_space_transform_crosses_transparent_edge_with_origin_style() {
let mut separator_style = ComputedStyle::initial();
separator_style.font_size = 23.0;
separator_style.word_space_transform = css::WordSpaceTransform {
replacement: Some(css::WordSpaceReplacement::Space),
auto_phrase: false,
};
let following_style = ComputedStyle::initial();
let transparent_edge = InlineItem::Atom(Box::new(InlineAtom::new(
InlineAtomContent::InlineEdge(InlineEdgeRole::BoxEdge(InlineBoxEdgeFragment {
logical_edge: InlineLogicalEdge::End,
physical_side: PhysicalSide::Right,
positioning_containing_block_id: None,
advance: 0.0,
paint_extent: 0.0,
})),
following_style.clone(),
None,
InlineSize::new(0.0, following_style.line_height),
0.0,
0.0,
None,
None,
)));
let mut items = Vec::new();
push_inline_text_run(
"a\u{200b}",
&separator_style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
items.push(transparent_edge);
push_inline_text_run(
"b",
&following_style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let separator = items
.iter()
.find_map(|item| match item {
InlineItem::Word(word)
if word.source
== InlineTextSource::WordSpaceTransform(
ExplicitWordSeparatorSource::AuthoredZeroWidthSpace,
) =>
{
Some(word)
}
_ => None,
})
.expect("the explicit separator should survive a transparent inline edge");
assert_eq!(separator.text, " ");
assert_eq!(separator.style.font_size, separator_style.font_size);
}
#[test]
fn word_space_transform_discards_separator_adjacent_to_forced_break() {
let mut style = ComputedStyle::initial();
style.white_space = WhiteSpace::Pre;
style.word_space_transform = css::WordSpaceTransform {
replacement: Some(css::WordSpaceReplacement::IdeographicSpace),
auto_phrase: false,
};
let mut items = Vec::new();
push_inline_text_run(
"a\u{200b}\n\u{200b}b",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let text = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(text, "ab");
assert!(!text.contains('\u{3000}'));
}
#[test]
fn word_space_transform_requires_text_on_both_sides() {
let mut style = ComputedStyle::initial();
style.white_space = WhiteSpace::Pre;
style.word_space_transform = css::WordSpaceTransform {
replacement: Some(css::WordSpaceReplacement::IdeographicSpace),
auto_phrase: false,
};
let mut items = Vec::new();
push_inline_text_run(
"\u{200b}a\u{200b}b\n\u{200b}c",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let text = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(text, "\u{200b}a\u{3000}bc");
assert_eq!(
items
.iter()
.filter(|item| matches!(
item,
InlineItem::Word(word)
if word.source
== InlineTextSource::WordSpaceTransform(
ExplicitWordSeparatorSource::AuthoredZeroWidthSpace
)
))
.count(),
1
);
}
#[test]
fn segment_break_uses_east_asian_width_instead_of_autospace_ideographs() {
let style = ComputedStyle::initial();
let mut items = Vec::new();
push_inline_text_run(
"A\n~",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let text = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(text, "A~");
}
#[test]
fn segment_break_uses_neighbors_outside_collapsed_space_sequence() {
let style = ComputedStyle::initial();
assert!(segment_break_is_removable(SegmentBreakContext {
before: '中',
after: '文',
before_is_currency_amount: false,
language: None,
}));
let mut items = Vec::new();
push_inline_text_run(
"中 \n 文",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let text = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(text, "中文");
}
#[test]
fn removable_segment_break_rejoins_one_typographic_run() {
let mut style = ComputedStyle::initial();
style.language = ContentLanguage::from_html_attribute("ja");
let mut items = Vec::new();
push_inline_text_run(
"Edge\n・\nChrome",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
let words = items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(words, ["Edge・Chrome"]);
}
#[test]
fn mandatory_unicode_breaks_force_lines_in_every_white_space_mode() {
for white_space in [WhiteSpace::Normal, WhiteSpace::NoWrap, WhiteSpace::PreWrap] {
let mut style = ComputedStyle::initial();
style.white_space = white_space;
let mut items = Vec::new();
push_inline_text_run(
"1\u{000c}2\u{000b}3\u{2028}4\u{2029}5\u{0085}6",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
assert_eq!(
items
.iter()
.filter(|item| matches!(item, InlineItem::Break(_)))
.count(),
5,
"{white_space:?} must retain every BK/NL boundary"
);
assert!(
items
.iter()
.filter_map(|item| match item {
InlineItem::Break(break_) => Some(break_),
_ => None,
})
.all(|break_| break_.origin == InlineBreakOrigin::Explicit),
"{white_space:?} must represent BK/NL as forced, not preserved segment breaks"
);
assert_eq!(
items
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>(),
"123456"
);
}
}
#[test]
fn cgj_remains_in_source_for_line_breaking_and_shaping_filtering() {
let style = ComputedStyle::initial();
let mut items = Vec::new();
push_inline_text_run(
"A\u{034f}",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut items,
);
normalize_inline_whitespace_items(&mut items);
assert!(matches!(
items.as_slice(),
[InlineItem::Word(word)] if word.text == "A\u{034f}"
));
}
#[test]
fn segment_break_skips_variation_selectors_but_not_hangul() {
let style = ComputedStyle::initial();
let mut removable = Vec::new();
push_inline_text_run(
"社\u{fe00}\n福\u{fe00}",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut removable,
);
normalize_inline_whitespace_items(&mut removable);
let removable_text = removable
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(removable_text, "社\u{fe00}福\u{fe00}");
let mut hangul = Vec::new();
push_inline_text_run(
"A\n한",
&style,
None,
0.0,
InlineVisualOffset::zero(),
&mut hangul,
);
normalize_inline_whitespace_items(&mut hangul);
let hangul_text = hangul
.iter()
.filter_map(|item| match item {
InlineItem::Word(word) => Some(word.text.as_str()),
_ => None,
})
.collect::<String>();
assert_eq!(hangul_text, "A 한");
}
}
pub(in crate::layout) fn push_inline_text_run(
text: &str,
style: &ComputedStyle,
link_target: Option<String>,
baseline_shift: f32,
visual_offset: InlineVisualOffset,
output: &mut Vec<InlineItem>,
) {
push_inline_text_run_with_source(
text,
style,
link_target,
baseline_shift,
visual_offset,
InlineTextSource::Normal,
output,
);
}
pub(in crate::layout) fn push_generated_inline_words_for_style(
text: &str,
style: &ComputedStyle,
link_target: Option<String>,
baseline_shift: f32,
visual_offset: InlineVisualOffset,
output: &mut Vec<InlineItem>,
) {
push_generated_inline_words_for_style_with_source(
text,
style,
link_target,
baseline_shift,
visual_offset,
InlineTextSource::Generated,
output,
);
}
pub(in crate::layout) fn push_generated_inline_words_for_style_with_source(
text: &str,
style: &ComputedStyle,
link_target: Option<String>,
baseline_shift: f32,
visual_offset: InlineVisualOffset,
source: InlineTextSource,
output: &mut Vec<InlineItem>,
) {
let normalized_style;
let style = if anonymous_inline_content_needs_normalized_style(style) {
normalized_style = normalized_anonymous_inline_content_style(style);
&normalized_style
} else {
style
};
push_inline_text_run_with_source(
text,
style,
link_target,
baseline_shift,
visual_offset,
source,
output,
);
}
pub(in crate::layout) fn push_inline_text_run_with_source(
text: &str,
style: &ComputedStyle,
link_target: Option<String>,
baseline_shift: f32,
visual_offset: InlineVisualOffset,
source: InlineTextSource,
output: &mut Vec<InlineItem>,
) {
if !text.is_empty() {
output.push(InlineItem::Word(Box::new(InlineWord {
text: text.to_string(),
style: inline_style(style),
baseline_shift,
visual_offset,
link_target: link_target.map(Rc::from),
mergeable: true,
source,
hanging_edges: InlineHangingEdges::default(),
excluded_positioning_geometry_source: None,
ancestor_inline_decorations: Vec::new().into(),
})));
}
}
pub(in crate::layout) fn normalize_inline_whitespace_items(items: &mut Vec<InlineItem>) {
let mut processor = InlineWhitespaceProcessor::default();
for item in std::mem::take(items) {
processor.push_item(item);
}
processor.flush();
normalize_inline_box_hanging_edge_ownership(&mut processor.output);
*items = processor.output;
}
fn normalize_inline_box_hanging_edge_ownership(items: &mut [InlineItem]) {
for item_index in 0..items.len() {
let InlineItem::Word(word) = &items[item_index] else {
continue;
};
if !inline_word_is_visible_for_hanging_edge(word) {
let InlineItem::Word(word) = &mut items[item_index] else {
unreachable!("the item was checked as an inline word")
};
word.hanging_edges = InlineHangingEdges::default();
continue;
}
let hanging_edges = word.hanging_edges;
let keeps_start = !hanging_edges.blocks_start
|| inline_word_is_adjacent_to_source_hanging_edge(
items,
item_index,
InlineLogicalEdge::Start,
);
let keeps_end = !hanging_edges.blocks_end
|| inline_word_is_adjacent_to_source_hanging_edge(
items,
item_index,
InlineLogicalEdge::End,
);
let InlineItem::Word(word) = &mut items[item_index] else {
unreachable!("the item was checked as an inline word")
};
word.hanging_edges.blocks_start &= keeps_start;
word.hanging_edges.blocks_end &= keeps_end;
}
}
fn inline_word_is_visible_for_hanging_edge(word: &InlineWord) -> bool {
let text = trim_css_collapsible_whitespace(&word.text);
!text.is_empty() && !text.chars().all(character_is_bidi_format_control)
}
fn inline_word_is_adjacent_to_source_hanging_edge(
items: &[InlineItem],
item_index: usize,
edge: InlineLogicalEdge,
) -> bool {
let source_edge_is_adjacent = |item: &InlineItem| match item {
InlineItem::Word(word) if inline_word_is_visible_for_hanging_edge(word) => Some(false),
InlineItem::Atom(atom)
if matches!(
atom.content(),
InlineAtomContent::InlineEdge(InlineEdgeRole::BoxEdge(box_edge))
if box_edge.logical_edge == edge
) =>
{
Some(true)
}
InlineItem::Word(_)
| InlineItem::Atom(_)
| InlineItem::StaticPositionSourceMarker(_)
| InlineItem::Float(_)
| InlineItem::Break(_)
| InlineItem::PageScopeStart(_)
| InlineItem::PageScopeEnd => None,
};
let result = match edge {
InlineLogicalEdge::Start => items[..item_index]
.iter()
.rev()
.find_map(source_edge_is_adjacent),
InlineLogicalEdge::End => items[item_index + 1..]
.iter()
.find_map(source_edge_is_adjacent),
};
if let Some(result) = result {
return result;
}
true
}
#[derive(Default)]
pub(in crate::layout) struct InlineWhitespaceProcessor {
pub(in crate::layout) output: Vec<InlineItem>,
pub(in crate::layout) run: String,
pub(in crate::layout) run_meta: Option<InlineTextRunMeta>,
pub(in crate::layout) run_is_document_space: bool,
pub(in crate::layout) output_ends_with_virtual_word_space: bool,
pub(in crate::layout) merge_next_run_after_removed_segment_break: bool,
pub(in crate::layout) last_text_character: Option<char>,
pub(in crate::layout) pending_segment_break: Option<InlineTextRunMeta>,
pending_segment_break_placement: PendingSegmentBreakPlacement,
pub(in crate::layout) pending_forced_segment_break: Option<PendingForcedSegmentBreak>,
pub(in crate::layout) pending_word_space_transform: Option<PendingWordSpaceTransform>,
}
#[derive(Clone)]
pub(in crate::layout) struct InlineTextRunMeta {
pub(in crate::layout) style: InlineStyle,
pub(in crate::layout) baseline_shift: f32,
pub(in crate::layout) visual_offset: InlineVisualOffset,
pub(in crate::layout) link_target: Option<Rc<str>>,
pub(in crate::layout) mergeable: bool,
pub(in crate::layout) source: InlineTextSource,
pub(in crate::layout) hanging_edges: InlineHangingEdges,
pub(in crate::layout) excluded_positioning_geometry_source:
Option<InlinePositioningContainingBlockId>,
pub(in crate::layout) ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
}
#[derive(Clone, Copy)]
struct InlineStreamItemIndex(usize);
#[derive(Clone, Copy, Default)]
enum PendingSegmentBreakPlacement {
#[default]
WithinCurrentInline,
BeforeInlineStart(InlineStreamItemIndex),
}
#[derive(Clone, Copy)]
pub(in crate::layout) struct InlinePlacement {
baseline: InlineBaselinePlacement,
pub(in crate::layout) visual_offset: InlineVisualOffset,
}
impl InlinePlacement {
pub(in crate::layout) fn new(baseline_shift: f32, visual_offset: InlineVisualOffset) -> Self {
Self {
baseline: InlineBaselinePlacement::from_inherited_glyph_displacement(
glyph_baseline_displacement_pt(baseline_shift),
),
visual_offset,
}
}
pub(in crate::layout) fn zero() -> Self {
Self::new(0.0, InlineVisualOffset::zero())
}
pub(in crate::layout) fn baseline_shift(self) -> f32 {
self.baseline.glyph_displacement().get()
}
pub(in crate::layout) fn with_added_baseline_placement(
self,
baseline: InlineBaselinePlacement,
) -> Self {
Self {
baseline: self.baseline.with_added(baseline),
..self
}
}
pub(in crate::layout) fn with_added_visual_offset(
self,
visual_offset: InlineVisualOffset,
) -> Self {
Self {
visual_offset: self.visual_offset.plus(visual_offset),
..self
}
}
}
#[derive(Clone, Copy)]
pub(in crate::layout) struct PendingForcedSegmentBreak {
pub(in crate::layout) preserve_at_end: bool,
pub(in crate::layout) clear: Clear,
pub(in crate::layout) origin: InlineBreakOrigin,
}
#[derive(Clone)]
pub(in crate::layout) struct PendingWordSpaceTransform {
pub(in crate::layout) replacement: css::WordSpaceReplacement,
pub(in crate::layout) meta: InlineTextRunMeta,
}
#[derive(Clone)]
pub(in crate::layout) struct IntrinsicInlineCollectionContext<'a> {
pub(in crate::layout) baseline_shift: f32,
pub(in crate::layout) visual_offset: InlineVisualOffset,
pub(in crate::layout) block_style: &'a ComputedStyle,
pub(in crate::layout) propagated_decoration_layers: Vec<css::TextDecorationLayer>,
}
impl<'a> IntrinsicInlineCollectionContext<'a> {
pub(in crate::layout) fn with_baseline_shift(self, baseline_shift: f32) -> Self {
Self {
baseline_shift,
..self
}
}
pub(in crate::layout) fn with_visual_offset(self, visual_offset: InlineVisualOffset) -> Self {
Self {
visual_offset,
..self
}
}
pub(in crate::layout) fn with_block_style(self, block_style: &'a ComputedStyle) -> Self {
Self {
block_style,
..self
}
}
pub(in crate::layout) fn with_propagated_decoration_layers(
self,
propagated_decoration_layers: Vec<css::TextDecorationLayer>,
) -> Self {
Self {
propagated_decoration_layers,
..self
}
}
}
pub(in crate::layout) fn propagated_decoration_layers_for_child(
ancestor_layers: &[css::TextDecorationLayer],
child_style: &ComputedStyle,
) -> Vec<css::TextDecorationLayer> {
let mut layers = ancestor_layers.to_vec();
for child_layer in child_style.text_decoration_origins.effective_layers() {
if !layers.iter().any(|ancestor_layer| {
Rc::ptr_eq(&ancestor_layer.origin_style, &child_layer.origin_style)
}) {
layers.push(child_layer.clone());
}
}
layers
}
#[derive(Debug, Clone, Default)]
pub(in crate::layout) struct TextDecorationPropagationContext {
layers: Vec<css::TextDecorationLayer>,
}
impl TextDecorationPropagationContext {
pub(in crate::layout) fn from_style(style: &ComputedStyle) -> Self {
Self {
layers: style.text_decoration_origins.effective_layers_vec(),
}
}
fn from_own_origin(style: &ComputedStyle) -> Self {
Self {
layers: style
.text_decoration_origins
.own_layer()
.cloned()
.into_iter()
.collect(),
}
}
pub(in crate::layout) fn for_child(&self, child_style: &ComputedStyle) -> Self {
if text_decoration_propagation_stops_at(child_style) {
return Self::from_own_origin(child_style);
}
Self {
layers: propagated_decoration_layers_for_child(&self.layers, child_style),
}
}
pub(in crate::layout) fn apply_to(&self, style: &mut ComputedStyle) {
apply_propagated_decoration_layers(style, &self.layers);
}
pub(in crate::layout) fn used_child_style(&self, child_style: &ComputedStyle) -> ComputedStyle {
let context = self.for_child(child_style);
let mut used_style = child_style.clone();
context.apply_to(&mut used_style);
used_style
}
}
fn text_decoration_propagation_stops_at(style: &ComputedStyle) -> bool {
matches!(style.position, Position::Absolute | Position::Fixed)
|| style.float != Float::None
|| style.display.is_atomic_inline()
}
pub(in crate::layout) fn apply_propagated_decoration_layers(
style: &mut ComputedStyle,
layers: &[css::TextDecorationLayer],
) {
style
.text_decoration_origins
.set_propagated_from_effective(layers);
}
impl InlineWhitespaceProcessor {
pub(in crate::layout) fn push_item(&mut self, item: InlineItem) {
let role = inline_item_boundary_role(&item);
match role {
InlineBoundaryRole::Text => {
let InlineItem::Word(word) = item else {
unreachable!("text boundary role must come from a word")
};
self.push_word(*word);
}
InlineBoundaryRole::TransparentTextBoundary
| InlineBoundaryRole::PageScopeStart
| InlineBoundaryRole::PageScopeEnd => {
debug_assert!(role.is_transparent_to_whitespace());
if self.pending_forced_segment_break.is_some() {
self.emit_forced_break();
}
self.flush_run();
if self.pending_segment_break.is_some()
&& matches!(
&item,
InlineItem::Atom(atom)
if matches!(
atom.content(),
InlineAtomContent::InlineEdge(InlineEdgeRole::BoxEdge(edge))
if edge.logical_edge == InlineLogicalEdge::Start
)
)
&& matches!(
self.pending_segment_break_placement,
PendingSegmentBreakPlacement::WithinCurrentInline
)
{
self.pending_segment_break_placement =
PendingSegmentBreakPlacement::BeforeInlineStart(InlineStreamItemIndex(
self.output.len(),
));
}
self.output.push(item);
}
InlineBoundaryRole::Float => {
if self.pending_forced_segment_break.is_some() {
self.emit_forced_break();
}
self.discard_pending_word_space_transform();
self.flush_run();
self.output.push(item);
}
InlineBoundaryRole::OpaqueAtomic | InlineBoundaryRole::IndependentFormattingContext => {
self.discard_pending_word_space_transform();
self.resolve_pending_before_boundary();
self.flush_run();
self.output.push(item);
if role.resets_text_context() {
self.reset_text_context();
}
}
InlineBoundaryRole::ForcedBreak => {
self.discard_pending_word_space_transform();
let clear = match item {
InlineItem::Break(break_) => break_.clear,
_ => Clear::None,
};
self.discard_pending_segment_breaks();
self.emit_forced_break_with_clear(clear);
}
}
}
pub(in crate::layout) fn push_word(&mut self, word: InlineWord) {
let meta = InlineTextRunMeta {
style: word.style,
baseline_shift: word.baseline_shift,
visual_offset: word.visual_offset,
link_target: word.link_target,
mergeable: word.mergeable,
source: word.source,
hanging_edges: word.hanging_edges,
excluded_positioning_geometry_source: word.excluded_positioning_geometry_source,
ancestor_inline_decorations: word.ancestor_inline_decorations,
};
for source_character in word.text.chars() {
let character = match classify_css_text_scalar(source_character) {
CssTextScalar::MandatoryLineBreak(_) => {
self.discard_pending_word_space_transform();
self.push_segment_break(&meta, true);
continue;
}
CssTextScalar::SegmentBreak => {
self.discard_pending_word_space_transform();
self.push_segment_break(&meta, false);
continue;
}
CssTextScalar::CarriageReturn | CssTextScalar::DocumentSpace => ' ',
CssTextScalar::Tab => '\t',
CssTextScalar::VisibleControl(control) => control.synthesized_glyph(),
CssTextScalar::Text(character) => character,
};
if character == '\u{200b}'
&& let Some(replacement) = meta.style.word_space_transform.replacement
&& self.last_text_character.is_some_and(|previous| previous != '\u{200b}')
{
self.resolve_pending_word_space_transform_before_text();
self.pending_word_space_transform = Some(PendingWordSpaceTransform {
replacement,
meta: meta.clone(),
});
} else if character == INLINE_BREAK {
self.discard_pending_word_space_transform();
self.push_segment_break(&meta, true);
} else if meta.style.white_space.collapses_spaces() && matches!(character, ' ' | '\t') {
self.resolve_pending_word_space_transform_before_text();
self.push_collapsible_space(&meta);
} else {
self.resolve_pending_word_space_transform_before_text();
self.push_text_character(character, &meta);
}
}
}
fn push_explicit_word_space_transform(
&mut self,
replacement: css::WordSpaceReplacement,
meta: &InlineTextRunMeta,
) {
let source = if meta.source == InlineTextSource::GeneratedWbr {
ExplicitWordSeparatorSource::HtmlWbr
} else {
ExplicitWordSeparatorSource::AuthoredZeroWidthSpace
};
match replacement {
css::WordSpaceReplacement::Space => {
self.flush_run();
self.push_word_run_with_source(
" ",
meta,
InlineTextSource::WordSpaceTransform(source),
);
self.output_ends_with_virtual_word_space = true;
self.last_text_character = Some(' ');
}
css::WordSpaceReplacement::IdeographicSpace => {
self.flush_run();
self.push_word_run_with_source(
"\u{3000}",
meta,
InlineTextSource::WordSpaceTransform(source),
);
self.last_text_character = Some('\u{3000}');
}
}
}
fn resolve_pending_word_space_transform_before_text(&mut self) {
let Some(pending) = self.pending_word_space_transform.take() else {
return;
};
if self.pending_forced_segment_break.is_some() {
return;
}
self.push_explicit_word_space_transform(pending.replacement, &pending.meta);
}
fn discard_pending_word_space_transform(&mut self) {
self.pending_word_space_transform = None;
}
pub(in crate::layout) fn push_segment_break(&mut self, meta: &InlineTextRunMeta, forced: bool) {
self.discard_pending_word_space_transform();
if forced || meta.style.white_space.preserves_newlines() {
if self.pending_forced_segment_break.is_some() {
self.emit_forced_break();
}
self.flush_run();
self.pending_segment_break = None;
self.pending_forced_segment_break = Some(PendingForcedSegmentBreak {
preserve_at_end: forced
|| meta.source.is_generated()
|| meta.style.white_space.preserves_newlines(),
clear: if meta.source.is_generated() {
meta.style.clear
} else {
Clear::None
},
origin: if forced || meta.source.is_generated() {
InlineBreakOrigin::Explicit
} else {
InlineBreakOrigin::PreservedSegment
},
});
} else if meta.style.white_space.collapses_spaces() {
self.flush_run();
if self.pending_segment_break.is_none() {
self.pending_segment_break_placement = PendingSegmentBreakPlacement::default();
}
self.pending_segment_break = Some(meta.clone());
} else {
self.push_text_character('\n', meta);
}
}
pub(in crate::layout) fn push_collapsible_space(&mut self, meta: &InlineTextRunMeta) {
if self.pending_forced_segment_break.is_some() || self.pending_segment_break.is_some() {
return;
}
self.flush_run();
if self.output_ends_with_virtual_word_space {
self.push_word_run(" ", meta);
self.output_ends_with_virtual_word_space = false;
self.last_text_character = Some(' ');
return;
}
if self.output_ends_at_space_or_line_start() {
self.promote_trailing_collapsible_space_wrap(meta);
return;
}
self.push_word_run(" ", meta);
self.last_text_character = Some(' ');
}
fn promote_trailing_collapsible_space_wrap(&mut self, meta: &InlineTextRunMeta) {
if !meta.style.allows_soft_wrap() {
return;
}
for item in self.output.iter_mut().rev() {
match item {
InlineItem::Word(word)
if word.style.white_space.collapses_spaces()
&& word.text.chars().all(is_css_collapsible_whitespace) =>
{
if !word.style.allows_soft_wrap() {
Rc::make_mut(&mut word.style).text_wrap_mode = css::TextWrapMode::Wrap;
}
return;
}
InlineItem::Atom(atom) if atom.content().is_box_edge() => {}
InlineItem::StaticPositionSourceMarker(_)
| InlineItem::PageScopeStart(_)
| InlineItem::PageScopeEnd
| InlineItem::Float(_) => {}
InlineItem::Word(_) | InlineItem::Break(_) | InlineItem::Atom(_) => return,
}
}
}
pub(in crate::layout) fn push_text_character(
&mut self,
character: char,
meta: &InlineTextRunMeta,
) {
if character != ' ' {
self.output_ends_with_virtual_word_space = false;
}
if character_is_bidi_format_control(character)
&& self.pending_forced_segment_break.is_some()
{
self.emit_forced_break();
}
let defers_segment_break_context =
character != '\u{200b}' && character_is_default_ignorable_code_point(character);
if !defers_segment_break_context {
self.resolve_pending_before_character(character);
}
if meta.style.white_space == WhiteSpace::BreakSpaces {
self.flush_run();
let mut buffer = [0; 4];
self.push_word_run(character.encode_utf8(&mut buffer), meta);
} else {
let character_is_document_space = matches!(character, ' ' | '\t');
if self.run.is_empty() {
self.run_meta = Some(meta.clone());
self.run_is_document_space = character_is_document_space;
} else if self.run_is_document_space != character_is_document_space
|| !self.run_meta_matches(meta)
{
self.flush_run();
self.run_meta = Some(meta.clone());
self.run_is_document_space = character_is_document_space;
}
self.run.push(character);
}
if !character_is_bidi_format_control(character) && !defers_segment_break_context {
self.last_text_character = Some(character);
}
}
pub(in crate::layout) fn resolve_pending_before_character(&mut self, next: char) {
if self.pending_forced_segment_break.is_some() {
self.emit_forced_break();
}
let Some(meta) = self.pending_segment_break.take() else {
return;
};
let placement = std::mem::take(&mut self.pending_segment_break_placement);
let previous = self
.last_text_character
.filter(|character| !is_css_collapsible_whitespace(*character))
.or_else(|| self.preceding_segment_break_character());
if previous.is_some_and(|previous| {
segment_break_is_removable(SegmentBreakContext {
before: previous,
after: next,
before_is_currency_amount: self.preceding_segment_break_token_has_currency(),
language: meta.style.language.as_deref(),
})
}) {
self.remove_trailing_collapsible_segment_whitespace();
self.merge_next_run_after_removed_segment_break = true;
self.last_text_character = previous;
return;
}
let output_len = self.output.len();
self.push_collapsible_space(&meta);
if let PendingSegmentBreakPlacement::BeforeInlineStart(InlineStreamItemIndex(
start_edge_index,
)) = placement
&& self.output.len() > output_len
&& matches!(self.output.last(), Some(InlineItem::Word(word)) if word.text == " ")
{
let mut space = self.output.pop().expect("checked trailing space");
let crossed_positioning_source = self.output.get(start_edge_index).and_then(|item| {
let InlineItem::Atom(atom) = item else {
return None;
};
let InlineAtomContent::InlineEdge(InlineEdgeRole::BoxEdge(edge)) = atom.content()
else {
return None;
};
(edge.logical_edge == InlineLogicalEdge::Start)
.then_some(edge.positioning_containing_block_id)
.flatten()
});
if let (Some(source), InlineItem::Word(word)) = (crossed_positioning_source, &mut space)
{
word.excluded_positioning_geometry_source = Some(source);
}
self.output.insert(start_edge_index, space);
}
}
fn remove_trailing_collapsible_segment_whitespace(&mut self) {
let mut remove = Vec::new();
for (index, item) in self.output.iter().enumerate().rev() {
match item {
InlineItem::Word(word)
if word.style.white_space.collapses_spaces()
&& word.text.chars().all(is_css_collapsible_whitespace) =>
{
remove.push(index);
}
InlineItem::Atom(atom) if atom.content().is_box_edge() => {}
_ => break,
}
}
for index in remove {
self.output.remove(index);
}
}
fn preceding_segment_break_character(&self) -> Option<char> {
for item in self.output.iter().rev() {
match item {
InlineItem::Word(word) => {
for character in word.text.chars().rev() {
if is_css_collapsible_whitespace(character)
|| (character != '\u{200b}'
&& character_is_default_ignorable_code_point(character))
{
continue;
}
return Some(character);
}
}
InlineItem::Atom(atom) if atom.content().is_box_edge() => {}
InlineItem::StaticPositionSourceMarker(_)
| InlineItem::PageScopeStart(_)
| InlineItem::PageScopeEnd
| InlineItem::Float(_) => {}
InlineItem::Break(_) | InlineItem::Atom(_) => return None,
}
}
None
}
fn preceding_segment_break_token_has_currency(&self) -> bool {
for item in self.output.iter().rev() {
match item {
InlineItem::Word(word) => {
return word.text.chars().any(character_is_currency_symbol);
}
InlineItem::Atom(atom) if atom.content().is_box_edge() => {}
InlineItem::StaticPositionSourceMarker(_)
| InlineItem::PageScopeStart(_)
| InlineItem::PageScopeEnd
| InlineItem::Float(_) => {}
InlineItem::Break(_) | InlineItem::Atom(_) => return false,
}
}
false
}
pub(in crate::layout) fn resolve_pending_before_boundary(&mut self) {
if self.pending_forced_segment_break.is_some() {
self.emit_forced_break();
}
if let Some(meta) = self.pending_segment_break.take() {
if !self.output_ends_at_space_or_line_start() {
self.push_collapsible_space(&meta);
}
}
}
pub(in crate::layout) fn emit_forced_break(&mut self) {
let clear = self
.pending_forced_segment_break
.map(|break_| break_.clear)
.unwrap_or(Clear::None);
let origin = self
.pending_forced_segment_break
.map(|break_| break_.origin)
.unwrap_or(InlineBreakOrigin::Explicit);
self.emit_forced_break_with_origin(clear, origin);
}
pub(in crate::layout) fn emit_forced_break_with_clear(&mut self, clear: Clear) {
self.emit_forced_break_with_origin(clear, InlineBreakOrigin::Explicit);
}
fn emit_forced_break_with_origin(&mut self, clear: Clear, origin: InlineBreakOrigin) {
self.flush_run();
self.pending_forced_segment_break = None;
self.pending_segment_break = None;
self.merge_next_run_after_removed_segment_break = false;
self.output
.push(InlineItem::Break(InlineBreak { clear, origin }));
self.last_text_character = None;
}
pub(in crate::layout) fn flush(&mut self) {
self.discard_pending_word_space_transform();
self.flush_run();
if self
.pending_forced_segment_break
.is_some_and(|break_| break_.preserve_at_end)
{
self.emit_forced_break();
} else {
self.discard_pending_segment_breaks();
}
}
pub(in crate::layout) fn flush_run(&mut self) {
if self.run.is_empty() {
return;
}
let text = std::mem::take(&mut self.run);
let meta = self
.run_meta
.take()
.expect("non-empty inline text run must carry metadata");
self.push_word_run(&text, &meta);
}
pub(in crate::layout) fn push_word_run(&mut self, text: &str, meta: &InlineTextRunMeta) {
self.push_word_run_with_source(text, meta, meta.source);
}
fn push_word_run_with_source(
&mut self,
text: &str,
meta: &InlineTextRunMeta,
source: InlineTextSource,
) {
if text.is_empty() {
return;
}
if self.merge_next_run_after_removed_segment_break {
self.merge_next_run_after_removed_segment_break = false;
if let Some(InlineItem::Word(previous)) = self.output.last_mut()
&& previous.style.as_ref() == meta.style.as_ref()
&& previous.baseline_shift == meta.baseline_shift
&& previous.visual_offset == meta.visual_offset
&& previous.link_target == meta.link_target
&& previous.mergeable == meta.mergeable
&& previous.source == source
&& previous.hanging_edges == meta.hanging_edges
&& previous.ancestor_inline_decorations == meta.ancestor_inline_decorations
{
previous.text.push_str(text);
return;
}
}
self.output.push(InlineItem::Word(Box::new(InlineWord {
text: text.to_string(),
style: Rc::clone(&meta.style),
baseline_shift: meta.baseline_shift,
visual_offset: meta.visual_offset,
link_target: meta.link_target.clone(),
mergeable: meta.mergeable,
source,
hanging_edges: meta.hanging_edges,
excluded_positioning_geometry_source: meta.excluded_positioning_geometry_source,
ancestor_inline_decorations: Rc::clone(&meta.ancestor_inline_decorations),
})));
}
pub(in crate::layout) fn run_meta_matches(&self, meta: &InlineTextRunMeta) -> bool {
self.run_meta.as_ref().is_some_and(|current| {
current.style.as_ref() == meta.style.as_ref()
&& current.baseline_shift == meta.baseline_shift
&& current.link_target == meta.link_target
&& current.mergeable == meta.mergeable
&& current.source == meta.source
&& current.hanging_edges == meta.hanging_edges
&& current.ancestor_inline_decorations == meta.ancestor_inline_decorations
})
}
pub(in crate::layout) fn discard_pending_segment_breaks(&mut self) {
self.pending_segment_break = None;
self.pending_segment_break_placement = PendingSegmentBreakPlacement::default();
self.pending_forced_segment_break = None;
}
pub(in crate::layout) fn reset_text_context(&mut self) {
self.last_text_character = None;
self.discard_pending_word_space_transform();
self.discard_pending_segment_breaks();
}
pub(in crate::layout) fn output_ends_at_space_or_line_start(&self) -> bool {
for item in self.output.iter().rev() {
match item {
InlineItem::Atom(atom) if atom.content().is_box_edge() => {}
InlineItem::StaticPositionSourceMarker(_) => {}
InlineItem::PageScopeStart(_) | InlineItem::PageScopeEnd => {}
InlineItem::Float(_) => {}
InlineItem::Word(_) => return inline_item_is_collapsible_space(item),
InlineItem::Break(_) => return true,
InlineItem::Atom(_) => return false,
}
}
true
}
}