use crate::model::{
control::Control,
paragraph::{LineSeg, Paragraph},
shape::{TextWrap, VertAlign, VertRelTo},
};
pub(crate) struct BandCrossingShift {
pub first_line: usize,
pub line_shift: i32,
pub frame_shift: i32,
}
pub(crate) fn band_crossing_line_shift(
para: &Paragraph,
next_frame_vpos: Option<i32>,
) -> Option<BandCrossingShift> {
let lines = ¶.line_segs;
if lines.len() < 2
|| para.stored_text_partition_is_dirty()
|| para.cell_format_vpos_dirty
|| lines.iter().any(|line| {
line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0 || line.line_height <= 0
})
|| lines
.windows(2)
.any(|pair| pair[1].vertical_pos < pair[0].vertical_pos)
{
return None;
}
let mut found = None;
for (control_index, control) in para.controls.iter().enumerate() {
let Control::Table(table) = control else {
continue;
};
let common = &table.common;
let v_off = crate::renderer::float_placement::signed_hwpunit(common.vertical_offset);
if common.treat_as_char
|| common.text_wrap != TextWrap::TopAndBottom
|| common.vert_rel_to != VertRelTo::Para
|| common.vert_align != VertAlign::Top
|| v_off <= 0
|| common.height == 0
|| common.height > i32::MAX as u32
{
continue;
}
let stored: Vec<&LineSeg> = lines.iter().collect();
let Some(anchor_index) =
crate::renderer::layout::stored_float_anchor_line_top(para, control_index, &stored)
.and_then(|top| lines.iter().rposition(|line| line.vertical_pos == top))
else {
continue;
};
let anchor = &lines[anchor_index];
let band_top = i64::from(anchor.vertical_pos) + i64::from(v_off);
if i64::from(anchor.vertical_pos) + i64::from(anchor.line_height) > band_top {
continue;
}
let band_bottom = band_top
+ i64::from(table.outer_margin_top)
+ i64::from(common.height)
+ i64::from(table.outer_margin_bottom);
if next_frame_vpos.map(i64::from) != Some(band_bottom)
|| lines
.iter()
.any(|line| (band_top..band_bottom).contains(&i64::from(line.vertical_pos)))
{
continue;
}
let Some(index) = (anchor_index + 1..lines.len()).find(|&index| {
let line = &lines[index];
i64::from(line.vertical_pos) < band_top
&& i64::from(line.vertical_pos) + i64::from(line.line_height) > band_top
}) else {
continue;
};
let line_shift = band_bottom - i64::from(lines[index].vertical_pos);
let last = lines.last()?;
let last_end = i64::from(last.vertical_pos)
+ i64::from(last.line_height)
+ i64::from(last.line_spacing.max(0));
let frame_shift = (last_end + line_shift).max(band_bottom) - last_end.max(band_bottom);
if found.is_some() {
return None;
}
found = Some(BandCrossingShift {
first_line: index,
line_shift: i32::try_from(line_shift).ok()?,
frame_shift: i32::try_from(frame_shift).ok()?,
});
}
found.filter(|shift| shift.line_shift > 0)
}