use super::{
CellUnit, LayoutEngine, NestedTableCut, ResolvedStyleSet, RowCutResult,
ROW_CUT_CAPACITY_FP_EPSILON_PX,
};
use crate::model::{
control::Control,
paragraph::LineSeg,
table::{Cell, Table},
};
#[derive(Clone, Copy)]
pub(super) enum CutHeight {
Capacity,
Occupied,
}
#[derive(Clone, Copy)]
pub(super) enum RowCutCapacity<'a> {
Content,
Physical {
deltas: &'a [f64],
allow_stored_tail: bool,
},
}
impl<'a> RowCutCapacity<'a> {
pub(super) fn deltas(self) -> Option<&'a [f64]> {
match self {
Self::Content => None,
Self::Physical { deltas, .. } => Some(deltas),
}
}
pub(super) fn allows_stored_tail(self) -> bool {
match self {
Self::Content => true,
Self::Physical {
allow_stored_tail, ..
} => allow_stored_tail,
}
}
}
impl LayoutEngine {
pub(in crate::renderer::layout) fn stored_reset_span_owns_closing_slot(
&self,
table: &Table,
cell: &Cell,
units: &[CellUnit],
end: usize,
) -> bool {
let Some((last, next)) = end
.checked_sub(1)
.and_then(|last| units.get(last).zip(units.get(end)))
else {
return false;
};
!last.reflowed_line_slot
&& last.para_idx == next.para_idx
&& next.page_frame_reset_before
&& self.stored_span_cut_preserves_line_slots(table, cell)
&& cell.paragraphs.get(last.para_idx).is_some_and(|para| {
!para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& last.vis_end.checked_sub(1).is_some_and(|line| {
para.line_segs
.get(line)
.is_some_and(|seg| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
})
})
}
pub(super) fn stored_complete_cell_slot_capacity(
&self,
cell: &Cell,
table: &Table,
units: &[CellUnit],
start: usize,
end: usize,
) -> Option<f64> {
if start != 0
|| end != units.len()
|| cell.row_span != 1
|| cell.vertical_align != crate::model::table::VerticalAlign::Top
|| cell.height > i32::MAX as u32
|| !self.stored_plain_fragment_table(table)
{
return None;
}
if crate::renderer::float_placement::stored_plain_cell_ink_height(cell).is_some() {
return None;
}
let last = units.last()?;
let para = cell.paragraphs.get(last.para_idx)?;
if last.empty_spacer
|| last.para_idx + 1 != cell.paragraphs.len()
|| last.vis_end != para.line_segs.len()
|| last.vis_start >= last.vis_end
|| last.following_line_advance != 0.0
{
return None;
}
let line = para.line_segs.last()?;
let gap = crate::renderer::hwpunit_to_px(line.line_spacing, self.dpi);
let (_, _, top, bottom) = self.resolve_cell_padding(cell, table);
let complete = units.iter().map(|unit| unit.height).sum::<f64>() + gap + top + bottom;
(gap > 0.0
&& crate::renderer::hwpunit_to_px(cell.height as i32, self.dpi)
> complete + crate::renderer::hwpunit_to_px(2, self.dpi))
.then_some(complete)
}
pub(crate) fn row_cut_has_plain_reflow_units(
&self,
table: &Table,
row: usize,
start_cut: &[usize],
available: f64,
styles: &ResolvedStyleSet,
) -> bool {
if !self.row_uses_outer_fragment_frame(table, row) {
return false;
}
let (cut, _) =
self.advance_row_cut_for_physical_band(table, row, start_cut, available, styles);
let mut has_reflow_line = false;
for (slot, index) in Self::row_cut_cell_order(table, row).into_iter().enumerate() {
let cell = &table.cells[index];
let units = self.cell_units(cell, table, styles);
let start = start_cut.get(slot).copied().unwrap_or(0).min(units.len());
let end = cut
.end_cut
.get(slot)
.copied()
.unwrap_or(start)
.clamp(start, units.len());
for unit in &units[start..end] {
if unit.nested_row.is_some()
|| unit.nested_table_fragment.is_some()
|| unit.mixed_nested_fragment
|| unit.top_and_bottom_flow
|| unit.non_inline_control_range.is_some()
{
return false;
}
has_reflow_line |= cell
.paragraphs
.get(unit.para_idx)
.is_some_and(crate::renderer::para_has_no_stored_line_segs);
}
}
has_reflow_line
}
pub(super) fn physical_start_after_leading_spacers(
&self,
cell: &Cell,
table: &Table,
units: &[CellUnit],
start: usize,
styles: &ResolvedStyleSet,
) -> usize {
if start == 0 {
return start;
}
let mut next = start.min(units.len());
while units
.get(next)
.is_some_and(|unit| self.is_free_leading_spacer(cell, table, unit, styles))
{
next += 1;
}
let restarts_after = units.get(next).is_some_and(|unit| {
unit.hard_break_before || unit.stored_frame_break_before || unit.page_frame_reset_before
});
if next > start && restarts_after {
next
} else {
start
}
}
fn unit_owns_stored_inline_table_frame(&self, cell: &Cell, unit: &CellUnit) -> bool {
if !(self.profile.get().hwp5_stored_pagination_layout()
|| self.profile.get().hwpx_stored_layout())
{
return false;
}
let Some(para) = cell.paragraphs.get(unit.para_idx) else {
return false;
};
if !para.text.trim().is_empty()
|| para.stored_text_partition_is_dirty()
|| para.cell_format_vpos_dirty
|| crate::renderer::para_has_no_stored_line_segs(para)
{
return false;
}
para.controls.iter().enumerate().any(|(index, control)| {
let Control::Table(child) = control else {
return false;
};
if !child.common.treat_as_char
|| child.common.height == 0
|| self
.render_normalization
.borrow()
.table_text_reflowed(child)
{
return false;
}
let Some(line_index) = super::super::control_line_seg_index(para, index) else {
return false;
};
let height = i64::from(child.common.height)
+ i64::from(child.outer_margin_top)
+ i64::from(child.outer_margin_bottom);
unit.vis_start <= line_index
&& line_index < unit.vis_end
&& para.line_segs.get(line_index).is_some_and(|line| {
line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& i64::from(line.line_height) == height
})
})
}
pub(crate) fn row_uses_outer_fragment_frame(&self, table: &Table, row: usize) -> bool {
!self
.nested_table_ptrs
.borrow()
.contains(&(table as *const Table as usize))
&& !Self::row_cut_cell_order(table, row).is_empty()
}
pub(crate) fn row_cut_uses_outer_line_frame(
&self,
table: &Table,
row: usize,
start_cut: &[usize],
available: f64,
styles: &ResolvedStyleSet,
) -> bool {
if !self.row_uses_outer_fragment_frame(table, row) {
return false;
}
if self.row_has_plain_line_units(table, row, styles) {
return true;
}
let (cut, _) =
self.advance_row_cut_for_physical_band(table, row, start_cut, available, styles);
let mut has_content = false;
for (slot, index) in Self::row_cut_cell_order(table, row).into_iter().enumerate() {
let units = self.cell_units(&table.cells[index], table, styles);
let start = start_cut.get(slot).copied().unwrap_or(0).min(units.len());
let end = cut
.end_cut
.get(slot)
.copied()
.unwrap_or(start)
.clamp(start, units.len());
for unit in &units[start..end] {
if self.unit_owns_stored_inline_table_frame(&table.cells[index], unit) {
return false;
}
if unit.nested_row.is_some()
|| unit.nested_table_fragment.is_some()
|| unit.mixed_nested_fragment
|| unit.top_and_bottom_flow
|| unit.non_inline_control_range.is_some()
{
return !self.table_uses_stored_fragment_coordinates(table);
}
has_content = true;
}
}
has_content
}
pub(super) fn cell_cut_flow_range(
&self,
cell: &Cell,
table: &Table,
units: &[CellUnit],
start: usize,
end: usize,
styles: &ResolvedStyleSet,
) -> std::ops::Range<usize> {
let mut first = start.min(units.len());
let mut last = end.clamp(first, units.len());
if first > 0 {
first = self
.physical_start_after_leading_spacers(cell, table, units, first, styles)
.min(last);
if last == units.len() {
while last > first
&& self.is_free_leading_spacer(cell, table, &units[last - 1], styles)
{
last -= 1;
}
}
}
first..last
}
pub(crate) fn carried_span_row_physical_height(
table: &Table,
row: usize,
start_cut: &[usize],
start_cut_is_block: bool,
carried: Option<f64>,
) -> Option<f64> {
let height = carried.filter(|height| height.is_finite() && *height >= 0.0)?;
if start_cut_is_block
|| !start_cut.is_empty()
|| table
.cells
.iter()
.any(|cell| usize::from(cell.row) == row && cell.row_span == 1)
{
return None;
}
table
.cells
.iter()
.any(|cell| {
let first = usize::from(cell.row);
cell.row_span > 1 && first <= row && row < first + usize::from(cell.row_span)
})
.then_some(height)
}
fn cut_trailing_advances(
&self,
table: &Table,
cell: &Cell,
units: &[CellUnit],
start: usize,
end: usize,
styles: &ResolvedStyleSet,
) -> (f64, f64) {
let stored =
self.native_saved_reset_cut_trailing_trim(table, cell, units, start, end, styles);
let Some(last) = end.checked_sub(1).and_then(|index| units.get(index)) else {
return (stored, stored);
};
if start >= end || end >= units.len() {
return (stored, stored);
}
let original_slot = !last.reflowed_line_slot
&& cell.paragraphs.get(last.para_idx).is_some_and(|para| {
!para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& last.vis_end.checked_sub(1).is_some_and(|line| {
para.line_segs.get(line).is_some_and(|seg| {
seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
== 0
})
})
});
let paragraph_end = last.para_idx != units[end].para_idx;
if self.stored_reset_span_owns_closing_slot(table, cell, units, end) {
return (0.0, 0.0);
}
let following = self.stored_span_line_tail_spacing(last);
let following = if paragraph_end && following > 0.0 {
following
+ cell
.paragraphs
.get(last.para_idx)
.and_then(|para| styles.para_styles.get(para.para_shape_id as usize))
.map_or(0.0, |style| style.spacing_after.max(0.0))
} else {
following
};
let capacity = if original_slot && paragraph_end {
following
} else {
0.0
};
let occupied = if paragraph_end || !original_slot {
following
} else {
0.0
};
(stored.max(capacity), stored.max(occupied))
}
pub(super) fn row_cut_capacity_trailing_trim(
&self,
table: &Table,
cell: &Cell,
units: &[CellUnit],
start: usize,
end: usize,
styles: &ResolvedStyleSet,
) -> f64 {
self.cut_trailing_advances(table, cell, units, start, end, styles)
.0
}
pub(super) fn physical_cut_trailing_trim(
&self,
table: &Table,
cell: &Cell,
units: &[CellUnit],
start: usize,
end: usize,
styles: &ResolvedStyleSet,
) -> f64 {
self.cut_trailing_advances(table, cell, units, start, end, styles)
.1
}
pub(super) fn projected_cut_trailing_advance(
&self,
child: &Table,
cut: &NestedTableCut,
styles: &ResolvedStyleSet,
purpose: CutHeight,
) -> f64 {
let [cell] = child.cells.as_slice() else {
return 0.0;
};
if cut.start_row != 0 || cut.end_row != 1 || cut.is_block_split || cut.start_cut_is_block {
return 0.0;
}
let units = self.cell_units(cell, child, styles);
let start = cut.start_cut.first().copied().unwrap_or(0).min(units.len());
let end = cut
.end_cut
.first()
.copied()
.unwrap_or(units.len())
.clamp(start, units.len());
if start == end || end == units.len() {
return 0.0;
}
let trailing = match purpose {
CutHeight::Capacity => {
self.row_cut_capacity_trailing_trim(child, cell, &units, start, end, styles)
}
CutHeight::Occupied => {
self.physical_cut_trailing_trim(child, cell, &units, start, end, styles)
}
};
trailing + self.continued_cut_nested_atom_tail(cell, &units, start, end, styles)
}
pub(crate) fn advance_row_cut_for_physical_band(
&self,
table: &Table,
row: usize,
start_cut: &[usize],
physical_budget: f64,
styles: &ResolvedStyleSet,
) -> (RowCutResult, f64) {
if let Some(cut) =
self.advance_reflow_external_row_cut(table, row, start_cut, physical_budget, styles)
{
return (cut, physical_budget);
}
let padding = self.row_remaining_visible_cell_padding(table, row, start_cut, styles);
let max_padding = padding.iter().copied().fold(0.0, f64::max);
let mut physical_cut_budget = physical_budget;
let mut previous_cut = None;
let mut allow_stored_tail = true;
loop {
let budget = (physical_cut_budget - max_padding).max(0.0);
let deltas: Vec<f64> = padding
.iter()
.map(|value| (physical_cut_budget - value).max(0.0) - budget)
.collect();
let cut = self.advance_row_cut_inner(
table,
row,
start_cut,
budget,
styles,
RowCutCapacity::Physical {
deltas: &deltas,
allow_stored_tail,
},
);
if let Some(fitted) = self.advance_reflow_nested_closing_band(
table,
row,
start_cut,
cut.clone(),
physical_budget,
styles,
) {
return (fitted, budget);
}
let required = self.row_cut_height(
table,
row,
start_cut,
&cut.end_cut,
styles,
CutHeight::Capacity,
);
let excess = (required - physical_budget).max(0.0);
if excess > ROW_CUT_CAPACITY_FP_EPSILON_PX && std::env::var("RHWP_DIAG_SCAN").is_ok() {
let owners: Vec<_> = Self::row_cut_cell_order(table, row)
.iter()
.enumerate()
.map(|(slot, &index)| {
let cell = &table.cells[index];
let units = self.cell_units(cell, table, styles);
let start = start_cut.get(slot).copied().unwrap_or(0).min(units.len());
let end = cut.end_cut[slot].clamp(start, units.len());
let advance = units[start..end]
.iter()
.map(|unit| unit.height)
.sum::<f64>();
let trim = self
.physical_cut_trailing_trim(table, cell, &units, start, end, styles);
(cell.col, start, end, advance, trim)
})
.collect();
eprintln!(
"DIAG_SCAN PHYSICAL_REFIT r={row} start={start_cut:?} end={:?} physical={physical_budget:.3} budget={budget:.3} required={required:.3} owners={owners:?}",
cut.end_cut,
);
}
if excess > ROW_CUT_CAPACITY_FP_EPSILON_PX && allow_stored_tail {
allow_stored_tail = false;
physical_cut_budget = physical_budget;
previous_cut = None;
continue;
}
if excess <= ROW_CUT_CAPACITY_FP_EPSILON_PX
|| physical_cut_budget <= 0.0
|| previous_cut.as_ref() == Some(&cut.end_cut)
{
return (cut, budget);
}
previous_cut = Some(cut.end_cut);
let additional_reserve = (required - cut.consumed_height - max_padding).max(0.0);
physical_cut_budget = (physical_cut_budget - excess)
.min(physical_budget - additional_reserve)
.max(0.0);
}
}
}