use crate::model::{control::Control, paragraph::Paragraph, shape::TextWrap};
use crate::renderer::render_tree::{RenderNode, RenderNodeType};
pub(super) struct ShapeHostFlow {
pub before: f64,
pub after: f64,
pub spacing_after: f64,
pub dpi: f64,
pub textless_host_end: Option<f64>,
}
pub(super) fn preserves_line_origin(
paragraph: &Paragraph,
para_index: usize,
control_index: usize,
column: &RenderNode,
flow: ShapeHostFlow,
) -> bool {
let ShapeHostFlow {
before: flow_before,
after: flow_after,
spacing_after,
dpi,
textless_host_end,
} = flow;
let common = match paragraph.controls.get(control_index) {
Some(Control::Picture(picture)) => &picture.common,
Some(Control::Shape(shape)) => shape.common(),
_ => return false,
};
if common.treat_as_char
|| !matches!(
common.text_wrap,
TextWrap::Square
| TextWrap::TopAndBottom
| TextWrap::Tight
| TextWrap::Through
| TextWrap::InFrontOfText
| TextWrap::BehindText
)
|| paragraph.stored_text_partition_is_dirty()
|| paragraph.cell_format_vpos_dirty
|| !flow_before.is_finite()
|| !flow_after.is_finite()
{
return false;
}
let roundoff = (flow_before.abs() + flow_after.abs()) * f64::EPSILON;
if (flow_after - flow_before).abs() > roundoff {
return false;
}
if let Some(end) = textless_host_end {
return same_coordinate(flow_before, end);
}
let Some(first) = paragraph.line_segs.first() else {
return false;
};
let mut origin = None;
let mut end = None;
for (index, stored) in paragraph.line_segs.iter().enumerate() {
if stored.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
|| stored.vertical_pos < first.vertical_pos
{
return false;
}
let Ok(index) = u32::try_from(index) else {
return false;
};
let Some(actual) = column.children.iter().find(|node| {
matches!(&node.node_type, RenderNodeType::TextLine(line)
if line.para_index == Some(para_index) && line.line_index == Some(index))
}) else {
return false;
};
let origin = *origin.get_or_insert(actual.bbox.y);
let expected_top =
origin + crate::renderer::hwpunit_to_px(stored.vertical_pos - first.vertical_pos, dpi);
let expected_height = crate::renderer::hwpunit_to_px(stored.line_height, dpi);
if !same_coordinate(actual.bbox.y, expected_top)
|| !same_coordinate(actual.bbox.height, expected_height)
{
return false;
}
end = Some(
actual.bbox.y
+ expected_height
+ crate::renderer::hwpunit_to_px(stored.line_spacing, dpi)
+ spacing_after,
);
}
end.is_some_and(|end| same_coordinate(flow_before, end))
}
fn same_coordinate(actual: f64, expected: f64) -> bool {
let roundoff = (actual.abs() + expected.abs() + 1.0) * f64::EPSILON * 8.0;
actual.is_finite() && expected.is_finite() && (actual - expected).abs() <= roundoff
}