use std::ops::Range;
mod alignment;
use alignment::RowEnding;
pub(crate) mod floating_shapes;
mod picture_rows;
pub(crate) use picture_rows::supports_picture_rows;
mod separator_spaces;
mod source_addresses;
pub(crate) use source_addresses::text_logical_starts;
mod table_rows;
pub(crate) use table_rows::{
standalone_table_fragment_owner, standalone_table_fragment_owner_with_storage,
supports_page_square_table_rows, supports_table_text_rows,
supports_table_text_rows_with_storage,
};
mod stored_host;
mod stored_square_rows;
pub(crate) use stored_host::{plan_stored_body_wide_host, plan_stored_empty_square_host};
use crate::model::{control::Control, paragraph::Paragraph, style::Alignment};
use super::{
float_placement::ObjectPlacementFrame,
height_measurer::MeasuredTable,
hwpunit_to_px,
layout::{estimate_text_width_unrounded, resolved_to_text_style},
layout_frame::{FrameExclusion, LayoutFrame},
px_to_hwpunit,
style_resolver::{detect_lang_category, ResolvedParaStyle, ResolvedStyleSet},
};
#[derive(Debug, Clone, PartialEq)]
pub enum InlineFlowContent {
Text {
range: Range<usize>,
style: u32,
lang: usize,
alignment_baseline: Option<f64>,
},
Table {
control: usize,
margin_left: f64,
margin_top: f64,
},
FloatingTable {
control: usize,
resolved_position: Option<(f64, f64)>,
},
FloatingShape {
control: usize,
},
Picture {
control: usize,
margin_left: f64,
margin_top: f64,
affect_line_spacing: bool,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct InlineFlowBox {
pub content: InlineFlowContent,
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
pub baseline: f64,
}
crate::storage::clone_fields!(InlineFlowBox, {content, x, y, width, height, baseline});
impl crate::storage::CloneWithStorage for InlineFlowContent {
fn clone_with_storage<S: crate::storage::Storage>(
&self,
_storage: &S,
) -> Result<Self, S::Error> {
Ok(self.clone())
}
}
impl InlineFlowBox {
fn alignment_baseline(&self) -> f64 {
match self.content {
InlineFlowContent::Text {
alignment_baseline: Some(value),
..
} => value,
_ => self.baseline,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct InlineFlowRow {
pub boxes: Range<usize>,
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
pub baseline: f64,
}
crate::storage::clone_fields!(InlineFlowRow, {boxes, x, y, width, height, baseline});
#[derive(Debug, Clone, PartialEq)]
pub struct InlineFlowPlan {
pub(crate) stored_empty_host: bool,
pub(crate) stored_float_host: bool,
pub(crate) text_rows: Option<Vec<crate::model::paragraph::LineSeg>>,
pub(crate) square_host_control: Option<usize>,
pub(crate) text_spacing_before: Option<f64>,
pub(crate) square_host_placement: Option<super::float_placement::ParagraphFloatPlacement>,
pub(crate) square_host_exclusion: Option<FrameExclusion>,
pub(crate) floating_shapes: Vec<floating_shapes::FloatingShapePlacement>,
pub start: f64,
pub end: f64,
pub boxes: Vec<InlineFlowBox>,
pub(crate) rows: Vec<InlineFlowRow>,
pub(crate) carved: bool,
next_row_top: f64,
fallback_font_size: f64,
}
crate::storage::clone_fields!(InlineFlowPlan, {stored_empty_host, stored_float_host, text_rows, square_host_control, text_spacing_before, square_host_placement, square_host_exclusion, floating_shapes, start, end, boxes, rows, carved, next_row_top, fallback_font_size});
impl InlineFlowPlan {
pub(crate) fn occupied_end(&self) -> f64 {
if self.rows.is_empty() {
return self.end;
}
self.rows
.iter()
.map(|row| row.y + row.height)
.fold(self.start, f64::max)
}
pub(crate) fn carved_by_any<'a>(
&self,
exclusions: impl IntoIterator<Item = &'a FrameExclusion>,
column_y: f64,
dpi: f64,
) -> bool {
self.carved
&& exclusions.into_iter().any(|exclusion| {
let top = hwpunit_to_px(exclusion.vertical.start, dpi) - column_y;
let bottom = hwpunit_to_px(exclusion.vertical.end, dpi) - column_y;
top < self.end && self.start < bottom
})
}
pub(crate) fn relative_to(&mut self, x: f64, y: f64) {
floating_shapes::relative_to(&mut self.floating_shapes, y);
self.start -= y;
self.end -= y;
self.next_row_top -= y;
if let Some(p) = &mut self.square_host_placement {
p.anchor_y -= y;
p.table_top -= y;
p.occupied_bottom -= y;
p.table_left = p.table_left.map(|left| left - x);
}
for item in &mut self.boxes {
if let InlineFlowContent::FloatingTable {
resolved_position: Some((left, top)),
..
} = &mut item.content
{
*left -= x;
*top -= y;
}
item.x -= x;
item.y -= y;
}
for row in &mut self.rows {
row.x -= x;
row.y -= y;
}
}
}
enum Atom {
Box(InlineFlowBox),
Float(FrameExclusion),
Break(InlineFlowBox),
}
#[derive(Clone, Copy, Default)]
struct RowMetrics {
width: f64,
baseline: f64,
descent: f64,
}
impl RowMetrics {
fn combined(self, other: Self) -> Self {
Self {
width: self.width + other.width,
baseline: self.baseline.max(other.baseline),
descent: self.descent.max(other.descent),
}
}
fn with(self, item: &InlineFlowBox) -> Self {
let baseline = item.alignment_baseline();
Self {
width: self.width + item.width,
baseline: self.baseline.max(baseline),
descent: self.descent.max(item.height - baseline),
}
}
}
pub(crate) fn supports(para: &Paragraph, width_hu: i32) -> bool {
if supports_picture_rows(para) {
return true;
}
para.controls.iter().any(|c| {
matches!(c, Control::Table(t)
if super::height_measurer::is_tac_table_inline_in_para(t, width_hu, para))
}) && para.controls.iter().all(|c| match c {
Control::Table(t) => t.common.treat_as_char,
Control::Picture(p) => !p.common.treat_as_char,
Control::Header(_)
| Control::Footer(_)
| Control::SectionDef(_)
| Control::ColumnDef(_)
| Control::PageNumberPos(_)
| Control::PageNumCtrl(_) => true,
_ => false,
})
}
pub(crate) fn plan(
para: &Paragraph,
para_index: usize,
styles: &ResolvedStyleSet,
tables: &[MeasuredTable],
frame: &ObjectPlacementFrame<'_>,
preceding: &[FrameExclusion],
) -> Option<InlineFlowPlan> {
match plan_with_storage(
para,
para_index,
styles,
tables,
frame,
preceding,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn plan_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
para_index: usize,
styles: &ResolvedStyleSet,
tables: &[MeasuredTable],
frame: &ObjectPlacementFrame<'_>,
preceding: &[FrameExclusion],
storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
let Some(style) = styles.para_styles.get(para.para_shape_id as usize) else {
return Ok(None);
};
let picture_rows = supports_picture_rows(para);
let top = frame.paragraph_y + style.spacing_before;
let positions = if para.text.is_empty() {
storage.filled(para.controls.len(), 0)?
} else {
para.try_control_text_positions(storage)?
};
let chars: Vec<_> = storage.collect(para.text.chars())?;
let mut controls: Vec<_> = storage.collect(positions.iter().copied().enumerate())?;
storage.stable_sort_by(&mut controls, |a, b| (a.1, a.0).cmp(&(b.1, b.0)))?;
let mut controls = controls.into_iter().peekable();
let mut atoms = Vec::new();
for position in 0..=chars.len() {
while controls.peek().is_some_and(|&(_, p)| p <= position) {
let Some((ci, _)) = controls.next() else {
return Ok(None);
};
match ¶.controls[ci] {
Control::Table(table) if !table.common.treat_as_char => {
storage.push(
&mut atoms,
Atom::Box(InlineFlowBox {
content: InlineFlowContent::FloatingTable {
control: ci,
resolved_position: None,
},
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
baseline: 0.0,
}),
)?;
}
Control::Shape(_) => atoms.push(Atom::Box(floating_shapes::anchor(ci))),
Control::Table(table) => {
let measured = tables
.iter()
.find(|m| m.para_index == para_index && m.control_index == ci);
let Some(measured) = measured else {
return Ok(None);
};
let left = hwpunit_to_px(i32::from(table.outer_margin_left), frame.dpi);
let right = hwpunit_to_px(i32::from(table.outer_margin_right), frame.dpi);
let top = hwpunit_to_px(i32::from(table.outer_margin_top), frame.dpi);
let bottom = hwpunit_to_px(i32::from(table.outer_margin_bottom), frame.dpi);
let height = measured.total_height + top + bottom;
let metrics = super::composer::frame_metrics_for_line(
height,
height,
style.line_spacing_type,
style.line_spacing,
frame.dpi,
);
storage.push(
&mut atoms,
Atom::Box(InlineFlowBox {
content: InlineFlowContent::Table {
control: ci,
margin_left: left,
margin_top: top,
},
x: 0.0,
y: 0.0,
width: hwpunit_to_px(table.common.width as i32, frame.dpi)
+ left
+ right,
height,
baseline: hwpunit_to_px(metrics.baseline_distance, frame.dpi),
}),
)?;
}
Control::Picture(picture) => {
if picture.common.treat_as_char {
storage.push(
&mut atoms,
Atom::Box(picture_rows::picture_box(picture, ci, style, frame.dpi)),
)?;
} else if let Some(exclusion) =
frame.picture_exclusion(picture, para, ci, styles)
{
storage.push(&mut atoms, Atom::Float(exclusion))?;
}
}
_ => {}
}
}
let Some(&ch) = chars.get(position) else {
break;
};
let stream_position = para
.char_offsets
.get(position)
.copied()
.unwrap_or(position as u32);
let cs = super::composer::find_active_char_shape(¶.char_shapes, stream_position);
let lang = detect_lang_category(ch);
let text_style = super::layout::try_resolved_to_text_style(styles, cs, lang, storage)?;
let text = storage.chars(std::iter::once(ch))?;
let width = estimate_text_width_unrounded(&text, &text_style);
let line_font_size = if picture_rows {
styles
.char_styles
.get(cs as usize)
.map_or(text_style.font_size, |s| s.font_size)
} else {
text_style.font_size
};
let metrics = super::composer::frame_metrics_for_line(
line_font_size,
12.0,
style.line_spacing_type,
style.line_spacing,
frame.dpi,
);
let height = hwpunit_to_px(metrics.line_height, frame.dpi);
let alignment_baseline = (picture_rows && style.vertical_alignment != 0).then(|| {
height * super::composer::inline_picture_ascent_ratio(style.vertical_alignment)
});
let mut item = InlineFlowBox {
content: InlineFlowContent::Text {
range: position..position + 1,
style: cs,
lang,
alignment_baseline,
},
x: 0.0,
y: 0.0,
width,
height,
baseline: hwpunit_to_px(metrics.baseline_distance, frame.dpi),
};
if ch == '\n' || ch == '\r' {
item.content = InlineFlowContent::Text {
range: position..position,
style: cs,
lang,
alignment_baseline,
};
item.width = 0.0;
storage.push(&mut atoms, Atom::Break(item))?;
} else {
storage.push(&mut atoms, Atom::Box(item))?;
}
}
if controls.peek().is_some() {
return Ok(None);
}
if picture_rows {
if let Some(anchor) = picture_rows::empty_host_text_box(para, styles, style, frame.dpi) {
atoms.push(Atom::Box(anchor));
}
}
if matches!(
atoms.last(),
Some(Atom::Box(InlineFlowBox {
content: InlineFlowContent::Picture { .. },
..
}))
) {
let end = chars.len();
let cs = super::composer::find_active_char_shape(
¶.char_shapes,
para.char_count.saturating_sub(1),
);
let font_size = styles
.char_styles
.get(cs as usize)
.map_or(12.0, |s| s.font_size);
let metrics = super::composer::frame_metrics_for_line(
font_size,
12.0,
style.line_spacing_type,
style.line_spacing,
frame.dpi,
);
let height = hwpunit_to_px(metrics.line_height, frame.dpi);
let alignment_baseline = (picture_rows && style.vertical_alignment != 0).then(|| {
height * super::composer::inline_picture_ascent_ratio(style.vertical_alignment)
});
storage.push(
&mut atoms,
Atom::Box(InlineFlowBox {
content: InlineFlowContent::Text {
range: end..end,
style: cs,
lang: 0,
alignment_baseline,
},
x: 0.0,
y: 0.0,
width: 0.0,
height,
baseline: hwpunit_to_px(metrics.baseline_distance, frame.dpi),
}),
)?;
}
let word_ranges = super::composer::text_word_ranges_with_storage(para, styles, storage)?;
let mut words = word_ranges.iter().peekable();
let mut word_metrics = std::collections::BTreeMap::new();
let mut attached_word_metrics = std::collections::BTreeMap::new();
let spaces = separator_spaces::classify_with_storage(&atoms, &chars, storage)?;
let mut index = 0;
while index < atoms.len() {
let Atom::Box(first) = &atoms[index] else {
index += 1;
continue;
};
let InlineFlowContent::Text {
range: first_range, ..
} = &first.content
else {
index += 1;
continue;
};
while words
.peek()
.is_some_and(|word| word.end <= first_range.start)
{
words.next();
}
let Some(word) = words
.peek()
.filter(|word| word.contains(&first_range.start))
else {
index += 1;
continue;
};
let start = first_range.start;
let mut metrics = RowMetrics::default();
while let Some(Atom::Box(item)) = atoms.get(index) {
let InlineFlowContent::Text { range, .. } = &item.content else {
break;
};
if !word.contains(&range.start) {
break;
}
metrics = metrics.with(item);
index += 1;
}
storage.insert_tree_map(&mut word_metrics, start, metrics)?;
if let Some(Atom::Box(next)) = atoms.get(index) {
if matches!(next.content, InlineFlowContent::Table { .. }) {
storage.insert_tree_map(&mut attached_word_metrics, start, metrics.with(next))?;
}
}
}
let mut exclusions = storage.collect(preceding.iter().cloned())?;
let horizontal = frame.container.x..frame.container.x + frame.container.width;
let mut result = InlineFlowPlan {
stored_empty_host: false,
stored_float_host: false,
text_rows: None,
square_host_control: None,
text_spacing_before: None,
square_host_placement: None,
square_host_exclusion: None,
floating_shapes: Vec::new(),
start: frame.paragraph_y,
end: top,
boxes: Vec::new(),
rows: Vec::new(),
carved: false,
next_row_top: top,
fallback_font_size: para
.char_shapes
.first()
.and_then(|r| styles.char_styles.get(r.char_shape_id as usize))
.map_or(12.0, |s| s.font_size),
};
let mut row = Vec::new();
let mut row_metrics = RowMetrics::default();
let mut float_tail_hang: Option<usize> = None;
let mut float_tail_hung_from: Option<usize> = None;
for atom in atoms {
match atom {
Atom::Float(exclusion) => {
let Some(()) = finish_row_with_storage(
&mut result,
&mut row,
&horizontal,
&exclusions,
style,
frame.dpi,
RowEnding::Forced(&chars),
float_tail_hung_from,
storage,
)?
else {
return Ok(None);
};
storage.push(&mut exclusions, exclusion)?;
row_metrics = RowMetrics::default();
}
Atom::Break(empty_line) => {
storage.push(&mut row, empty_line)?;
let Some(()) = finish_row_with_storage(
&mut result,
&mut row,
&horizontal,
&exclusions,
style,
frame.dpi,
RowEnding::Forced(&chars),
float_tail_hung_from,
storage,
)?
else {
return Ok(None);
};
row_metrics = RowMetrics::default();
}
Atom::Box(mut item) => {
if ![item.width, item.height, item.baseline]
.iter()
.all(|v| v.is_finite())
|| item.width < 0.0
|| (item.height <= 0.0
&& !matches!(
item.content,
InlineFlowContent::FloatingTable { .. }
| InlineFlowContent::FloatingShape { .. }
))
{
return Ok(None);
}
let row_horizontal =
paragraph_row_horizontal(&horizontal, style, result.boxes.is_empty());
let row_width = row_horizontal.end - row_horizontal.start;
if row.is_empty() {
float_tail_hang = None;
float_tail_hung_from = None;
}
if let InlineFlowContent::Text { range, .. } = &item.content {
if spaces.float_tail.contains(&range.start)
&& row_metrics.width + item.width > row_width + 0.01
&& separator_spaces::has_flow_content(&row, &chars)
{
let left = *float_tail_hang.get_or_insert_with(|| {
let after_object = matches!(
row.last().map(|last| &last.content),
Some(
InlineFlowContent::Table { .. }
| InlineFlowContent::Picture { .. }
)
);
let after_char = range
.start
.checked_sub(1)
.is_some_and(|previous| !chars[previous].is_whitespace());
if after_object || after_char {
2
} else {
1
}
});
if left > 0 {
float_tail_hung_from.get_or_insert(row.len());
item.width = 0.0;
row_metrics = row_metrics.with(&item);
storage.push(&mut row, item)?;
float_tail_hang = Some(left - 1);
if left == 1 {
let Some(()) = finish_row_with_storage(
&mut result,
&mut row,
&horizontal,
&exclusions,
style,
frame.dpi,
RowEnding::Soft(&chars),
float_tail_hung_from,
storage,
)?
else {
return Ok(None);
};
row_metrics = RowMetrics::default();
float_tail_hang = None;
float_tail_hung_from = None;
}
continue;
}
}
}
let object_separator = matches!(&item.content, InlineFlowContent::Text { range, .. }
if spaces.object.contains(&range.start));
let first_overhang_space = matches!(&item.content, InlineFlowContent::Text { range, .. }
if spaces.first_object.contains(&range.start))
&& separator_spaces::has_flow_content(&row, &chars)
&& row_metrics.width <= row_width + 0.01
&& row_metrics.width + item.width > row_width + 0.01;
let oversized_cut = match (&item.content, row.first()) {
(InlineFlowContent::Text { range, .. }, Some(first))
if spaces.wrap.contains(&range.start) && first.width > row_width =>
{
let control = match &first.content {
InlineFlowContent::Table { control, .. }
| InlineFlowContent::Picture { control, .. } => Some(*control),
_ => None,
};
control.and_then(|control| {
positions.get(control).map(|&start| {
let object_end = (range.start == start)
.then(|| (px_to_hwpunit(first.width, frame.dpi), 0));
super::composer::overflowing_space_cut(
start,
range.start,
px_to_hwpunit(row_metrics.width + item.width, frame.dpi),
0,
px_to_hwpunit(row_width, frame.dpi),
object_end,
)
})
})
}
_ => None,
};
let keep_oversized_space = matches!(oversized_cut, Some(None));
let absorb_oversized_space = matches!(oversized_cut,
Some(Some(cut)) if matches!(&item.content,
InlineFlowContent::Text { range, .. } if cut == range.end));
if matches!(&item.content, InlineFlowContent::Text { range, .. }
if spaces.wrap.contains(&range.start) || spaces.trailing.contains(&range.start))
&& row_metrics.width + item.width > row_width + 0.01
&& !first_overhang_space
&& !keep_oversized_space
&& separator_spaces::has_flow_content(&row, &chars)
{
item.width = 0.0;
if object_separator || absorb_oversized_space {
storage.push(&mut row, item)?;
let Some(()) = finish_row_with_storage(
&mut result,
&mut row,
&horizontal,
&exclusions,
style,
frame.dpi,
RowEnding::Soft(&chars),
float_tail_hung_from,
storage,
)?
else {
return Ok(None);
};
row_metrics = RowMetrics::default();
continue;
}
}
let lookahead = match &item.content {
InlineFlowContent::Text { range, .. } => attached_word_metrics
.get(&range.start)
.copied()
.or_else(|| {
word_metrics
.get(&range.start)
.filter(|metrics| metrics.width <= row_width + 0.01)
.copied()
})
.unwrap_or_else(|| RowMetrics::default().with(&item)),
_ => RowMetrics::default().with(&item),
};
let moves_existing_row = if row.is_empty() {
false
} else {
let Some(old) = row_geometry_with_storage(
row_metrics,
&row_horizontal,
result.next_row_top,
&exclusions,
style,
frame.dpi,
storage,
)?
else {
return Ok(None);
};
let Some(next) = row_geometry_with_storage(
row_metrics.combined(lookahead),
&row_horizontal,
result.next_row_top,
&exclusions,
style,
frame.dpi,
storage,
)?
else {
return Ok(None);
};
next.1 > old.1 + 0.01
};
if !row.is_empty()
&& ((lookahead.width > 0.0
&& row_metrics.width + lookahead.width > row_width + 0.01
&& !first_overhang_space
&& !keep_oversized_space)
|| (moves_existing_row && !keep_oversized_space))
{
let Some(()) = finish_row_with_storage(
&mut result,
&mut row,
&horizontal,
&exclusions,
style,
frame.dpi,
RowEnding::Soft(&chars),
float_tail_hung_from,
storage,
)?
else {
return Ok(None);
};
row_metrics = RowMetrics::default();
}
row_metrics = row_metrics.with(&item);
storage.push(&mut row, item)?;
}
}
}
let Some(()) = finish_row_with_storage(
&mut result,
&mut row,
&horizontal,
&exclusions,
style,
frame.dpi,
RowEnding::ParagraphEnd(&chars),
float_tail_hung_from,
storage,
)?
else {
return Ok(None);
};
result.end = if style.line_spacing_type == crate::model::style::LineSpacingType::Percent {
result.next_row_top
} else {
result.end.max(result.next_row_top)
} + style.spacing_after;
Ok((result.start.is_finite() && result.end.is_finite()).then_some(result))
}
#[allow(clippy::too_many_arguments)]
fn finish_row_with_storage<S: crate::storage::Storage>(
plan: &mut InlineFlowPlan,
row: &mut Vec<InlineFlowBox>,
horizontal: &Range<f64>,
exclusions: &[FrameExclusion],
style: &ResolvedParaStyle,
dpi: f64,
ending: RowEnding<'_>,
hung_from: Option<usize>,
storage: &S,
) -> Result<Option<()>, S::Error> {
if row.is_empty() {
return Ok(Some(()));
}
let mut row_metrics = row
.iter()
.fold(RowMetrics::default(), |metrics, item| metrics.with(item));
if row_metrics.baseline + row_metrics.descent == 0.0 {
let metrics = super::composer::frame_metrics_for_line(
plan.fallback_font_size,
plan.fallback_font_size,
style.line_spacing_type,
style.line_spacing,
dpi,
);
row_metrics.baseline = hwpunit_to_px(metrics.baseline_distance, dpi);
row_metrics.descent = hwpunit_to_px(metrics.line_height - metrics.baseline_distance, dpi);
}
let baseline = row_metrics.baseline;
let height = row_metrics.baseline + row_metrics.descent;
if let Some(chars) = ending.trimmed_chars() {
row_metrics.width -= row
.iter()
.rev()
.take_while(|item| {
matches!(&item.content, InlineFlowContent::Text { range, .. }
if chars[range.clone()].iter().all(|ch| *ch == ' '))
})
.map(|item| item.width)
.sum::<f64>();
}
let row_horizontal = paragraph_row_horizontal(horizontal, style, plan.boxes.is_empty());
let Some((mut x, y, carved, available_width)) = row_geometry_with_storage(
row_metrics,
&row_horizontal,
plan.next_row_top,
exclusions,
style,
dpi,
storage,
)?
else {
return Ok(None);
};
plan.carved |= carved;
let gaps = alignment::gaps_with_storage(
row,
ending,
style.alignment,
available_width - row_metrics.width,
storage,
)?;
row_metrics.width += gaps.iter().sum::<f64>();
let has_table = row
.iter()
.any(|b| matches!(b.content, InlineFlowContent::Table { .. }));
let spacing_font = |item: &InlineFlowBox| {
matches!(
item.content,
InlineFlowContent::Text { .. }
| InlineFlowContent::Picture {
affect_line_spacing: true,
..
}
)
.then_some(item.height)
};
let hung_from = hung_from.unwrap_or(row.len()).min(row.len());
let row_font_size = row[..hung_from]
.iter()
.filter_map(spacing_font)
.reduce(f64::max)
.unwrap_or(plan.fallback_font_size);
let row_font_size = row[hung_from..]
.iter()
.filter_map(spacing_font)
.fold(row_font_size, f64::max);
let first_box = plan.boxes.len();
let row_x = x;
for (index, mut item) in row.drain(..).enumerate() {
item.x = x;
item.y = if matches!(
item.content,
InlineFlowContent::FloatingTable { .. } | InlineFlowContent::FloatingShape { .. }
) {
y
} else {
y + baseline - item.alignment_baseline()
};
let advance = item.width + gaps[index];
if matches!(item.content, InlineFlowContent::Text { .. }) {
item.width = advance;
}
x += advance;
storage.push(&mut plan.boxes, item)?;
}
storage.push(
&mut plan.rows,
InlineFlowRow {
boxes: first_box..plan.boxes.len(),
x: row_x,
y,
width: row_metrics.width,
height,
baseline,
},
)?;
let metrics = super::composer::frame_metrics_for_line(
row_font_size,
plan.fallback_font_size,
style.line_spacing_type,
style.line_spacing,
dpi,
);
let gap = hwpunit_to_px(metrics.line_spacing, dpi);
let signed_gap =
!has_table || style.line_spacing_type == crate::model::style::LineSpacingType::Percent;
plan.next_row_top = y + height + if signed_gap { gap } else { gap.max(0.0) };
plan.end = plan.end.max(y + height);
Ok(Some(()))
}
fn paragraph_row_horizontal(
horizontal: &Range<f64>,
style: &ResolvedParaStyle,
first: bool,
) -> Range<f64> {
let indent = super::equation_tac_flow::paragraph_effective_margin_left(
0.0,
style.indent,
usize::from(!first),
);
horizontal.start + indent..horizontal.end
}
fn row_geometry_with_storage<S: crate::storage::Storage>(
metrics: RowMetrics,
horizontal: &Range<f64>,
top: f64,
exclusions: &[FrameExclusion],
style: &ResolvedParaStyle,
dpi: f64,
storage: &S,
) -> Result<Option<(f64, f64, bool, f64)>, S::Error> {
let width = metrics.width;
let height = metrics.baseline + metrics.descent;
let base = px_to_hwpunit(horizontal.start, dpi)..px_to_hwpunit(horizontal.end, dpi);
let Some(base_width) = base.end.checked_sub(base.start).filter(|w| *w > 0) else {
return Ok(None);
};
let mut frame = LayoutFrame::new(
base.clone(),
px_to_hwpunit(top, dpi),
storage.collect(exclusions.iter().cloned())?,
);
frame.minimum_width = px_to_hwpunit(width, dpi).max(1).min(base_width);
let intervals = frame.try_carve(px_to_hwpunit(height, dpi).max(1), storage)?;
let lane = if style.alignment == Alignment::Right {
intervals.last()
} else {
intervals.first()
};
let Some(lane) = lane.cloned() else {
return Ok(None);
};
let left = hwpunit_to_px(lane.start, dpi);
let spare = (hwpunit_to_px(lane.end - lane.start, dpi) - width).max(0.0);
let x = left
+ match style.alignment {
Alignment::Right => spare,
Alignment::Center => spare / 2.0,
_ => 0.0,
};
let y = hwpunit_to_px(frame.top, dpi).max(top);
let carved = y > top + 0.01 || lane.start > base.start || lane.end < base.end;
Ok(Some((
x,
y,
carved,
hwpunit_to_px(lane.end - lane.start, dpi),
)))
}
pub(crate) fn supports_plain_text(para: &Paragraph) -> bool {
super::para_has_no_stored_line_segs(para)
&& !para.text.trim().is_empty()
&& para.controls.is_empty()
}
pub(crate) fn plan_plain_text(
para: &Paragraph,
styles: &ResolvedStyleSet,
placement: &ObjectPlacementFrame<'_>,
preceding: &[FrameExclusion],
) -> Option<InlineFlowPlan> {
match plan_plain_text_with_storage(
para,
styles,
placement,
preceding,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn plan_plain_text_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
placement: &ObjectPlacementFrame<'_>,
preceding: &[FrameExclusion],
storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
if !supports_plain_text(para) && !supports_stored_plain_text(para) {
return Ok(None);
}
plan_text_rows_with_storage(para, styles, placement, preceding, storage)
}
pub(crate) fn supports_stored_plain_text(para: &Paragraph) -> bool {
!super::para_has_no_stored_line_segs(para)
&& !para.text.trim().is_empty()
&& para.controls.is_empty()
}
pub(crate) fn supports_square_float_host(para: &Paragraph) -> bool {
super::para_has_no_stored_line_segs(para)
&& !para.text.trim().is_empty()
&& para
.controls
.iter()
.any(super::composer::control_is_square_float_object)
&& para.controls.iter().all(|control| match control {
Control::Picture(picture) => picture.caption.is_none(),
Control::Shape(shape) => {
super::composer::control_is_square_float_object(control)
&& super::composer::shape_caption_for_layout(shape).is_none()
}
Control::SectionDef(_)
| Control::ColumnDef(_)
| Control::PageNumberPos(_)
| Control::PageNumCtrl(_) => true,
_ => false,
})
&& super::composer::supports_picture_band_frame_controls(para)
}
pub(crate) fn plan_square_float_host_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
placement: &ObjectPlacementFrame<'_>,
preceding: &[FrameExclusion],
storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
if !supports_square_float_host(para) {
return Ok(None);
}
let mut exclusions = storage.collect(preceding.iter().cloned())?;
for (index, control) in para.controls.iter().enumerate() {
let own = match control {
Control::Picture(picture) => placement.picture_exclusion(picture, para, index, styles),
Control::Shape(shape) => placement.shape_exclusion(shape),
_ => None,
};
if let Some(own) = own {
storage.push(&mut exclusions, own)?;
}
}
plan_text_rows_with_storage(para, styles, placement, &exclusions, storage)
}
fn plan_text_rows_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
placement: &ObjectPlacementFrame<'_>,
preceding: &[FrameExclusion],
storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
use super::composer::{layout_paragraph_in_frame_with_storage, ParagraphBox};
let Some(style) = styles.para_styles.get(para.para_shape_id as usize) else {
return Ok(None);
};
if style.head_type != crate::model::style::HeadType::None {
return Ok(None);
}
let mut exclusions = storage.collect(preceding.iter().cloned())?;
let text_top = placement.paragraph_y + style.spacing_before;
let dx = px_to_hwpunit(placement.column.x, placement.dpi);
let dy = px_to_hwpunit(text_top, placement.dpi);
for e in &mut exclusions {
e.horizontal = e.horizontal.start.saturating_sub(dx)..e.horizontal.end.saturating_sub(dx);
e.vertical = e.vertical.start.saturating_sub(dy)..e.vertical.end.saturating_sub(dy);
}
let paragraph_box =
ParagraphBox::body_for_style(placement.column.width, Some(style), placement.dpi);
if !paragraph_box.is_usable() {
return Ok(None);
}
let mut frame = paragraph_box.frame_with(0, exclusions);
let Some(rows) =
layout_paragraph_in_frame_with_storage(para, &mut frame, styles, placement.dpi, storage)?
else {
return Ok(None);
};
let mut clear_frame = paragraph_box.frame(0);
let Some(clear_rows) = layout_paragraph_in_frame_with_storage(
para,
&mut clear_frame,
styles,
placement.dpi,
storage,
)?
else {
return Ok(None);
};
let same_rows = rows.len() == clear_rows.len()
&& rows.iter().zip(&clear_rows).all(|(a, b)| {
a.text_start == b.text_start
&& a.vertical_pos == b.vertical_pos
&& a.column_start == b.column_start
&& a.segment_width == b.segment_width
});
let end = text_top + hwpunit_to_px(frame.top, placement.dpi) + style.spacing_after;
Ok(Some(InlineFlowPlan {
stored_empty_host: false,
stored_float_host: false,
start: placement.paragraph_y,
end,
boxes: Vec::new(),
rows: Vec::new(),
carved: !same_rows,
next_row_top: end,
fallback_font_size: 12.0,
text_rows: Some(rows),
square_host_control: None,
text_spacing_before: None,
square_host_placement: None,
square_host_exclusion: None,
floating_shapes: Vec::new(),
}))
}
pub(crate) fn plan_square_table_host(
para: &Paragraph,
para_index: usize,
styles: &ResolvedStyleSet,
tables: &[MeasuredTable],
column_width: f64,
dpi: f64,
) -> Option<InlineFlowPlan> {
use super::float_placement::{signed_hwpunit, ParagraphFloatFlow, ParagraphFloatPlacement};
use super::layout_frame::FrameExclusionPolicy;
use crate::model::shape::{HorzAlign, HorzRelTo, TextFlow, VertAlign, VertRelTo};
let invisible_unstored = super::para_has_no_stored_line_segs(para)
&& !para
.text
.chars()
.any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}' && !ch.is_whitespace());
let uncached = super::is_no_lineseg_visible_text_host(para) || invisible_unstored;
if !uncached
&& (!para
.text
.chars()
.any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}' && !ch.is_whitespace())
|| styles.hwp3_variant
|| super::composer::stored_rows_cross_physical_frame(para))
{
return None;
}
let control = para.controls.iter().position(|c| {
matches!(c, Control::Table(t)
if !t.common.treat_as_char && t.common.text_wrap == crate::model::shape::TextWrap::Square)
})?;
let unstored_host_companion = |c: &Control| {
use crate::model::shape::{TextWrap, VertRelTo};
let common = match c {
Control::Picture(p) => &p.common,
Control::Shape(s) => s.common(),
_ => return false,
};
uncached
&& !common.treat_as_char
&& (matches!(
common.text_wrap,
TextWrap::InFrontOfText | TextWrap::BehindText
) || (matches!(common.text_wrap, TextWrap::Square)
&& matches!(common.vert_rel_to, VertRelTo::Page | VertRelTo::Paper)))
};
if para.controls.iter().enumerate().any(|(i, c)| {
i != control
&& !super::composer::control_is_width_neutral_marker(c)
&& !matches!(c, Control::Picture(p) if !p.common.treat_as_char
&& matches!(p.common.text_wrap,
crate::model::shape::TextWrap::InFrontOfText
| crate::model::shape::TextWrap::BehindText))
&& !unstored_host_companion(c)
}) {
return None;
}
let style = styles.para_styles.get(para.para_shape_id as usize)?;
let mut text = para.clone();
text.controls
.retain(super::composer::control_is_width_neutral_marker);
text.line_segs.clear();
let Control::Table(table) = ¶.controls[control] else {
return None;
};
if invisible_unstored
&& !super::is_no_lineseg_visible_text_host(para)
&& super::unstored_empty_square_table_host_geometry_px(
para,
table,
column_width,
styles,
Some(style),
dpi,
)
.is_some()
{
return None;
}
let measured = tables
.iter()
.find(|m| m.para_index == para_index && m.control_index == control)?;
let c = &table.common;
if c.vert_rel_to != VertRelTo::Para
|| !matches!(c.vert_align, VertAlign::Top | VertAlign::Inside)
{
return None;
}
if table.caption.as_ref().is_some_and(|cap| {
matches!(
cap.direction,
crate::model::shape::CaptionDirection::Left
| crate::model::shape::CaptionDirection::Right
)
}) {
return None;
}
let (ref_left, ref_width) = match c.horz_rel_to {
HorzRelTo::Column => (0.0, column_width),
HorzRelTo::Para => (
style.margin_left,
column_width - style.margin_left - style.margin_right,
),
_ => return None,
};
let ml = hwpunit_to_px(i32::from(table.outer_margin_left), dpi);
let mr = hwpunit_to_px(i32::from(table.outer_margin_right), dpi);
let object_width = hwpunit_to_px(c.width as i32, dpi) + ml + mr;
let offset = hwpunit_to_px(signed_hwpunit(c.horizontal_offset), dpi);
let outer_left = match c.horz_align {
HorzAlign::Left | HorzAlign::Inside => ref_left + offset,
HorzAlign::Center => ref_left + (ref_width - object_width) / 2.0 + offset,
HorzAlign::Right | HorzAlign::Outside => ref_left + ref_width - object_width - offset,
};
if invisible_unstored && !super::is_no_lineseg_visible_text_host(para) {
let min_band = hwpunit_to_px(1440, dpi);
let left_band = outer_left.max(0.0);
let right_band = column_width - (outer_left + object_width);
if left_band < min_band && right_band < min_band {
return None;
}
}
let box_ = super::composer::ParagraphBox::body_for_style(column_width, Some(style), dpi);
let stored_rows = stored_square_rows::source(para, control, table, measured, &box_, dpi);
let spacing_before =
if para.line_segs.is_empty() && std::env::var("RHWP_EXP_BODY_FRESH").is_err() {
0.0
} else {
style.spacing_before
};
let geometry = |anchor_offset_hwp| {
let outer_top = hwpunit_to_px(
signed_hwpunit(c.vertical_offset).saturating_add(anchor_offset_hwp),
dpi,
);
let table_top = outer_top + hwpunit_to_px(i32::from(table.outer_margin_top), dpi);
let occupied_bottom = table_top
+ measured.total_height
+ hwpunit_to_px(i32::from(table.outer_margin_bottom), dpi);
let placement = ParagraphFloatPlacement {
flow: ParagraphFloatFlow::Exclusion,
anchor_y: 0.0,
stored_host_origin: None,
stored_successor_line_origin: None,
table_left: Some(outer_left + ml),
table_top,
occupied_bottom,
};
let exclusion = FrameExclusion {
horizontal: px_to_hwpunit(outer_left, dpi)
..px_to_hwpunit(outer_left + object_width, dpi),
vertical: px_to_hwpunit(outer_top, dpi)..px_to_hwpunit(occupied_bottom, dpi),
policy: match c.text_flow {
TextFlow::BothSides => FrameExclusionPolicy::BothSides,
TextFlow::LargestOnly => FrameExclusionPolicy::LargestSide,
TextFlow::LeftOnly => FrameExclusionPolicy::LeftSide,
TextFlow::RightOnly => FrameExclusionPolicy::RightSide,
},
};
let mut text_exclusion = exclusion.clone();
let spacing_hu = px_to_hwpunit(spacing_before, dpi);
text_exclusion.vertical.start -= spacing_hu;
text_exclusion.vertical.end -= spacing_hu;
(
placement,
exclusion,
box_.frame_with(0, vec![text_exclusion]),
)
};
let (mut placement, mut exclusion, mut frame) = geometry(
stored_rows
.as_ref()
.map_or(0, |source| source.anchor_offset_hwp),
);
let projected = stored_rows
.as_ref()
.and_then(|source| stored_square_rows::project(para, source, &mut frame));
let uses_stored_rows = projected.is_some();
let rows = if let Some(rows) = projected {
rows
} else {
(placement, exclusion, frame) = geometry(0);
super::composer::layout_paragraph_in_frame(&text, &mut frame, styles, dpi)?
};
if !uses_stored_rows
&& !uncached
&& rows.len() == para.line_segs.len()
&& rows.iter().zip(¶.line_segs).all(|(row, source)| {
row.column_start == source.column_start && row.segment_width == source.segment_width
})
{
return None;
}
let mut rows = rows;
let mut flow_top_hu = frame.top;
if invisible_unstored && rows.len() == 1 {
if let Some((height, spacing, _)) =
super::unstored_overlay_table_host_line_metrics(para, styles, Some(style))
{
let row = &mut rows[0];
let height_hu = px_to_hwpunit(height, dpi);
if height_hu > row.line_height {
row.baseline_distance += height_hu - row.line_height;
row.text_height = row.text_height.max(height_hu);
row.line_height = height_hu;
row.line_spacing = px_to_hwpunit(spacing, dpi);
flow_top_hu =
flow_top_hu.max(row.vertical_pos + row.line_height + row.line_spacing);
}
}
}
let end = spacing_before + hwpunit_to_px(flow_top_hu, dpi) + style.spacing_after;
Some(InlineFlowPlan {
stored_empty_host: false,
stored_float_host: false,
text_rows: Some(rows),
square_host_control: Some(control),
text_spacing_before: Some(spacing_before),
square_host_placement: Some(placement),
square_host_exclusion: Some(exclusion),
floating_shapes: Vec::new(),
start: 0.0,
end,
boxes: Vec::new(),
rows: Vec::new(),
carved: true,
next_row_top: end,
fallback_font_size: 12.0,
})
}