use crate::renderer::typeset::notes::footnotes::boundary::{
native_hwp5_existing_footnote_reset_boundary, native_hwp5_first_footnote_overlap_break_line,
native_hwp5_footnote_reset_fragments, NativeHwp5FootnoteFragmentSplit,
};
use crate::renderer::typeset::notes::footnotes::measure::{
composed_footnote_content_height, queued_table_footnote_content_height,
};
use crate::document_core::queries::rendering::body_pile_stays_on_anchor_page;
use crate::model::control::Control;
use crate::model::footnote::{Footnote, FootnoteShape};
use crate::model::header_footer::HeaderFooterApply;
use crate::model::page::{ColumnDef, ColumnType, PageDef};
use crate::model::paragraph::{ColumnBreakType, LineSeg, Paragraph};
use crate::model::shape::CaptionDirection;
use crate::renderer::composer::{compose_paragraph, first_text_line, ComposedParagraph};
use crate::renderer::float_placement::{
is_last_para_topbottom_float, is_page_bottom_fixed_float, is_para_topbottom_float,
is_textless_coanchored_float_host, signed_hwpunit,
stored_visible_anchor_band_host_line_advance_from_vpos, FloatLaneSet,
};
use crate::renderer::height_cursor::HeightCursor;
use crate::renderer::height_measurer::{stored_square_picture_has_adjacent_text, MeasuredTable};
use crate::renderer::layout::table_layout::native_terminal_child_host_line_spacing;
use crate::renderer::layout::{
border_width_to_px, endnote_last_column_tail_overflows_frame,
ENDNOTE_COLUMN_BOTTOM_BLEED_TOLERANCE_PX, ENDNOTE_LAST_COLUMN_SPLIT_BLEED_PX,
};
use crate::renderer::page_layout::PageLayoutInfo;
use crate::renderer::style_resolver::ResolvedStyleSet;
use crate::renderer::{
format_number, hwpunit_to_px, NumberFormat as RenderNumberFormat, DEFAULT_DPI,
};
use self::controls::deferred::{DeferredTableControl, DeferredTableFlushPoint};
use self::paragraph::boundary::hwpx_explicit_page_break_tail_line;
use self::paragraph::line_queries::{
composed_line_char_end, line_has_strict_tac_control, line_has_text_span, line_has_visible_text,
};
use self::paragraph::metrics::FormattedParagraph;
use self::paragraph::stored_lines::{
next_boundary_reverts_spacing_trim, spacing_trim_restorable,
stored_ladder_encodes_spacing_before,
};
use self::stored_table_frame::{
table_declared_height_has_stored_cell_content_frame,
table_declared_object_covers_cell_row_frames,
};
use super::pagination::{
estimate_footnote_note_height, footnote_between_notes_margin_px,
footnote_separator_overhead_px, ColumnContent, EndnoteDeferral, EndnoteParaSource, EndnoteRef,
FootnoteFragment, FootnoteRef, FootnoteSource, HeaderFooterRef, PageContent, PageItem,
PaginationResult,
};
const ENDNOTE_PAGE_OFFCANVAS_GUARD_PX: f64 = 56.0;
pub(crate) fn stored_line_restarts_page(
prev: &crate::model::paragraph::LineSeg,
next: &crate::model::paragraph::LineSeg,
) -> bool {
(prev.tag | next.tag) & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& next.vertical_pos <= 0
&& prev.vertical_pos.saturating_add(prev.line_height) > 5000
}
fn has_majority_fullpage_images(fullpage_count: usize, noninline_picture_count: usize) -> bool {
fullpage_count >= 2 && fullpage_count.saturating_mul(2) > noninline_picture_count
}
fn flow_noninline_picture(ctrl: &Control) -> Option<&crate::model::image::Picture> {
match ctrl {
Control::Picture(pic)
if !pic.common.treat_as_char
&& !matches!(
pic.common.text_wrap,
crate::model::shape::TextWrap::BehindText
| crate::model::shape::TextWrap::InFrontOfText
) =>
{
Some(pic)
}
_ => None,
}
}
use self::table::continuation::{
BlockTableContinuationContext, BlockTableContinuationPreparedState,
BlockTableContinuationSource, PendingTableFootnoteFragment, TableContinuationCursor,
TableContinuationIteration,
};
pub(crate) use self::table::continuation::{ResumablePaginationStep, ResumableTablePaginationJob};
use self::table::scan::{BlockRowScanVars, BlockTableRowScan};
fn empty_paragraph_fallback_line_metrics(
para: &Paragraph,
styles: &ResolvedStyleSet,
para_style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
hwp3_legacy_caps: bool,
) -> Option<(f64, f64)> {
if let Some((height, leading, _)) =
crate::renderer::reflow_float_host_line::neutral_anchor_metrics(
para,
styles,
para_style,
hwp3_legacy_caps,
DEFAULT_DPI,
)
{
return Some((height, leading));
}
let controls_flow_neutral = crate::renderer::empty_host_controls_are_flow_neutral(para);
if std::env::var("RHWP_DIAG_EMPTYP").is_ok() && !para.controls.is_empty() {
eprintln!(
"DIAG_EMPTYP text={:?} ctrls={} neutral={} segs={} cc={}",
para.text.chars().take(6).collect::<String>(),
para.controls.len(),
controls_flow_neutral,
para.line_segs.len(),
para.char_count,
);
}
if !para.text.trim().is_empty()
|| !(para.controls.is_empty() || controls_flow_neutral)
|| !para.line_segs.is_empty()
|| (para.char_count == 0 && para.controls.is_empty())
{
return None;
}
let char_shape_id =
para.char_shape_id_at(0)
.or_else(|| para.char_shapes.first().map(|cs| cs.char_shape_id))? as usize;
let char_style = styles.char_styles.get(char_shape_id)?;
let font_size = char_style.font_size;
if font_size <= 0.0 {
return None;
}
if hwp3_legacy_caps {
let small_empty_para_max_font = hwpunit_to_px(1000, DEFAULT_DPI);
if font_size > small_empty_para_max_font + 0.1 {
return None;
}
let meaningful_empty_para_min_font = hwpunit_to_px(800, DEFAULT_DPI);
if !char_style.bold && font_size < meaningful_empty_para_min_font - 0.1 {
return None;
}
}
let ls_val = para_style.map(|s| s.line_spacing).unwrap_or(160.0);
let ls_type = para_style
.map(|s| s.line_spacing_type)
.unwrap_or(crate::model::style::LineSpacingType::Percent);
Some(crate::renderer::corrected_line_metrics(
0.0, 0.0, font_size, ls_type, ls_val,
))
}
fn raw_table_ctrl_height_px(table: &crate::model::table::Table, dpi: f64) -> Option<f64> {
let range = crate::model::shape::common_obj_offsets::HEIGHT;
if table.raw_ctrl_data.len() < range.end {
return None;
}
let height = u32::from_le_bytes(table.raw_ctrl_data[range].try_into().ok()?);
(height > 0).then(|| hwpunit_to_px(height as i32, dpi))
}
#[derive(Debug, Clone)]
struct TableBreakToken {
start_row: usize,
cell_content_offsets: Option<Vec<f64>>,
}
crate::storage::clone_fields!(TableBreakToken, {start_row, cell_content_offsets});
#[derive(Debug, Clone)]
struct TableCellFootnote {
number: u16,
cell_path: Vec<crate::renderer::pagination::TableFootnotePathEntry>,
row: usize,
content_height: f64,
fragment_split: Option<NativeHwp5FootnoteFragmentSplit>,
}
crate::storage::clone_fields!(TableCellFootnote, {number, cell_path, row, content_height, fragment_split});
#[derive(Debug, Clone)]
pub(in crate::renderer::typeset) struct OwnLineNote {
pub para_index: usize,
pub line: usize,
pub control_index: usize,
pub number: u16,
pub content_height: f64,
pub lines: Vec<(f64, f64)>,
pub stored_split: Option<NativeHwp5FootnoteFragmentSplit>,
}
#[derive(Debug)]
struct FormattedTable {
external_flow: Option<crate::renderer::float_placement::ReflowExternalTableFlow>,
row_heights: Vec<f64>,
cell_spacing: f64,
header_row_count: usize,
host_spacing: HostSpacing,
effective_height: f64,
total_height: f64,
caption_height: f64,
is_tac: bool,
cumulative_heights: Vec<f64>,
page_break: crate::model::table::TablePageBreak,
cells: Vec<crate::renderer::height_measurer::MeasuredCell>,
table_footnote_height: f64,
table_footnote_count: usize,
table_footnotes: Vec<TableCellFootnote>,
strict_following_plain_text_fit: bool,
}
#[derive(Debug, Clone, Copy)]
struct VisibleFloatExclusion {
para_index: usize,
top: f64,
bottom: f64,
}
crate::storage::clone_copy!(VisibleFloatExclusion);
#[derive(Debug, Clone)]
struct DeferredSquarePictureControl {
para_index: usize,
control_index: usize,
wrap_target_para_indices: Vec<usize>,
wrap_anchor: crate::renderer::pagination::WrapAnchorRef,
}
crate::storage::clone_fields!(DeferredSquarePictureControl, {para_index, control_index, wrap_target_para_indices, wrap_anchor});
#[derive(Debug, Clone)]
enum DeferredStoredFrameKind {
Picture,
Table,
AbsoluteShape,
}
impl crate::storage::CloneWithStorage for DeferredStoredFrameKind {
fn clone_with_storage<S: crate::storage::Storage>(
&self,
storage: &S,
) -> Result<Self, S::Error> {
match self {
Self::Picture => Ok(Self::Picture),
Self::Table => Ok(Self::Table),
Self::AbsoluteShape => Ok(Self::AbsoluteShape),
}
}
}
#[derive(Debug, Clone)]
struct DeferredStoredFrameControl {
target_page: Option<usize>,
kind: DeferredStoredFrameKind,
para_index: usize,
control_index: usize,
placement: crate::renderer::float_placement::ParagraphFloatPlacement,
following_body_para_index: Option<usize>,
}
crate::storage::clone_fields!(DeferredStoredFrameControl, {target_page, kind, para_index, control_index, placement, following_body_para_index});
#[derive(Debug, Clone, Copy)]
struct HostSpacing {
before: f64,
after: f64,
column_top_before: f64,
host_line_spacing: f64,
spacing_after_only: f64,
terminal_outer_bottom_flow: f64,
after_for_fit: f64,
}
crate::storage::clone_copy!(HostSpacing);
pub struct TypesetEngine {
dpi: f64,
section_column_spacing_hu: std::cell::Cell<Option<i32>>,
profile: std::cell::Cell<crate::model::provenance::LayoutCompatibilityProfile>,
uniform_filler_ladder: std::cell::Cell<bool>,
float_carve_evidence:
std::cell::RefCell<Vec<crate::renderer::float_placement::FloatCarveEvidence>>,
format_next_stored_vpos: std::cell::Cell<Option<i32>>,
render_normalization:
std::sync::Arc<crate::renderer::render_normalization::RenderNormalizationOverlay>,
endnote_measure_memo: std::cell::RefCell<notes::endnotes::measure_memo::EndnoteMeasureMemo>,
}
const SINGLE_ROW_DECLARED_TRUST_MAX_RATIO: f64 = 1.5;
const MIN_TOP_KEEP_PX: f64 = 25.0;
#[inline]
fn row_split_meets_min_top_keep(
content_height: f64,
painted_height: f64,
use_painted_height: bool,
) -> bool {
let keep_height = if use_painted_height {
painted_height
} else {
content_height
};
keep_height >= MIN_TOP_KEEP_PX
}
fn row_has_stored_same_vpos_split_signal(table: &crate::model::table::Table, row: usize) -> bool {
table
.cells
.iter()
.filter(|cell| cell.row as usize == row)
.any(|cell| {
cell.paragraphs.iter().any(|paragraph| {
paragraph.line_segs.windows(2).any(|pair| {
pair.iter().all(|seg| {
seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
}) && pair[0].vertical_pos > 0
&& pair[1].vertical_pos == pair[0].vertical_pos
&& pair[1].column_start == pair[0].column_start
&& pair[1].segment_width == pair[0].segment_width
})
})
})
}
fn row_has_stored_cross_paragraph_zero_reset(
table: &crate::model::table::Table,
row: usize,
) -> bool {
use crate::model::paragraph::LineSeg;
table
.cells
.iter()
.filter(|cell| cell.row as usize == row)
.any(|cell| {
let Some(paragraphs) = cell.paragraphs.get(..3) else {
return false;
};
if paragraphs
.iter()
.any(|para| !para.controls.is_empty() || para.text.trim().is_empty())
{
return false;
}
let [first] = paragraphs[0].line_segs.as_slice() else {
return false;
};
let [second] = paragraphs[1].line_segs.as_slice() else {
return false;
};
let Some(third) = paragraphs[2].line_segs.first() else {
return false;
};
[first, second, third].iter().all(|seg| {
seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& seg.line_height > 0
&& seg.column_start == first.column_start
&& seg.segment_width == first.segment_width
}) && first.vertical_pos == 0
&& second.vertical_pos == 0
&& third.vertical_pos > 0
&& i64::from(third.vertical_pos)
== i64::from(second.line_height) + i64::from(second.line_spacing.max(0))
})
}
pub(crate) fn is_reparsed_single_column_cell_split_row(
table: &crate::model::table::Table,
row: usize,
) -> bool {
if table.col_count != 2 || row >= table.row_count as usize {
return false;
}
let mut row_cells = table
.cells
.iter()
.filter(|cell| cell.row as usize == row)
.collect::<Vec<_>>();
row_cells.sort_by_key(|cell| cell.col);
let matching_padding = row_cells.len() == 2
&& row_cells[0].padding.left == row_cells[1].padding.left
&& row_cells[0].padding.right == row_cells[1].padding.right
&& row_cells[0].padding.top == row_cells[1].padding.top
&& row_cells[0].padding.bottom == row_cells[1].padding.bottom;
if row_cells.len() != 2
|| row_cells[0].col != 0
|| row_cells[1].col != 1
|| row_cells
.iter()
.any(|cell| cell.col_span != 1 || cell.row_span != 1)
|| row_cells[0].width.abs_diff(row_cells[1].width) > 1
|| row_cells[0].height != row_cells[1].height
|| row_cells[0].border_fill_id != row_cells[1].border_fill_id
|| !matching_padding
{
return false;
}
let cell_has_content = |cell: &&crate::model::table::Cell| {
cell.paragraphs
.iter()
.any(|para| !para.text.is_empty() || !para.controls.is_empty())
};
let cell_is_template_empty = |cell: &&crate::model::table::Cell| {
cell.paragraphs.len() == 1
&& cell.paragraphs[0].text.is_empty()
&& cell.paragraphs[0].controls.is_empty()
&& !cell.paragraphs[0].has_para_text
&& cell.paragraphs[0].char_count <= 1
};
let content_cells = row_cells
.iter()
.filter(|cell| cell_has_content(cell))
.copied()
.collect::<Vec<_>>();
let template_cells = row_cells
.iter()
.filter(|cell| cell_is_template_empty(cell))
.copied()
.collect::<Vec<_>>();
if content_cells.len() != 1 || template_cells.len() != 1 {
return false;
}
let content_cell = content_cells[0];
let template_cell = template_cells[0];
if content_cell.col != 0 || template_cell.col != 1 {
return false;
}
let Some(source_para) = content_cell.paragraphs.first() else {
return false;
};
let template_para = &template_cell.paragraphs[0];
let zeroed_instance_clone = source_para.raw_header_extra.len() >= 10
&& source_para.raw_header_extra.len() == template_para.raw_header_extra.len()
&& source_para.raw_header_extra[6..10]
.iter()
.any(|byte| *byte != 0)
&& template_para.raw_header_extra[6..10]
.iter()
.all(|byte| *byte == 0)
&& source_para.raw_header_extra[..6] == template_para.raw_header_extra[..6]
&& source_para.raw_header_extra[10..] == template_para.raw_header_extra[10..];
let cloned_first_char_shape = template_para.char_shapes.len()
== source_para.char_shapes.len().min(1)
&& template_para
.char_shapes
.iter()
.zip(source_para.char_shapes.iter())
.all(|(template, source)| {
template.start_pos == source.start_pos
&& template.char_shape_id == source.char_shape_id
});
let cloned_first_line = template_para.line_segs.len() == 1
&& source_para
.line_segs
.first()
.zip(template_para.line_segs.first())
.is_some_and(|(source, template)| {
source.text_start == template.text_start
&& source.vertical_pos == template.vertical_pos
&& source.line_height == template.line_height
&& source.text_height == template.text_height
&& source.baseline_distance == template.baseline_distance
&& source.line_spacing == template.line_spacing
&& source.column_start == template.column_start
&& source.segment_width == template.segment_width
&& source.tag == template.tag
});
if !zeroed_instance_clone
|| content_cell.raw_list_extra != template_cell.raw_list_extra
|| content_cell.list_header_width_ref != template_cell.list_header_width_ref
|| content_cell.text_direction != template_cell.text_direction
|| content_cell.vertical_align != template_cell.vertical_align
|| content_cell.apply_inner_margin != template_cell.apply_inner_margin
|| content_cell.is_header != template_cell.is_header
|| source_para.para_shape_id != template_para.para_shape_id
|| source_para.style_id != template_para.style_id
|| !cloned_first_char_shape
|| !cloned_first_line
{
return false;
}
let mut other_cells = table
.cells
.iter()
.filter(|cell| cell.row as usize != row)
.peekable();
other_cells.peek().is_some()
&& other_cells.all(|cell| cell.col == 0 && cell.col_span == table.col_count)
}
fn partial_rowbreak_fragment_spacing_px(
table: &crate::model::table::Table,
first_fragment_host_before: f64,
is_continuation: bool,
repeat_outer_margin: bool,
repeat_cellbreak_outer_margin: bool,
dpi: f64,
) -> (f64, f64) {
let repeats_outer_margin = !table.common.treat_as_char
&& is_para_topbottom_float(&table.common)
&& match table.layout_page_break() {
crate::model::table::TablePageBreak::RowBreak => repeat_outer_margin,
crate::model::table::TablePageBreak::CellBreak => repeat_cellbreak_outer_margin,
crate::model::table::TablePageBreak::None => false,
};
let before = if is_continuation {
if repeats_outer_margin {
hwpunit_to_px(table.outer_margin_top as i32, dpi)
} else {
0.0
}
} else {
first_fragment_host_before
};
let bottom = if repeats_outer_margin {
hwpunit_to_px(table.outer_margin_bottom as i32, dpi)
} else {
0.0
};
(before, bottom)
}
fn empty_host_float_first_fragment_reserve_px(
para: &Paragraph,
table: &crate::model::table::Table,
fragment_outer_bottom: f64,
has_source_text_first_frame: bool,
caption_overhead: f64,
caption_is_top: bool,
dpi: f64,
) -> f64 {
if fragment_outer_bottom > 0.0
|| has_source_text_first_frame
|| !is_para_topbottom_float(&table.common)
|| signed_hwpunit(table.common.vertical_offset) != 0
|| para_has_non_whitespace_text(para)
{
return 0.0;
}
hwpunit_to_px(table.outer_margin_bottom as i32, dpi).max(0.0)
+ if caption_is_top {
0.0
} else {
caption_overhead
}
}
fn column_def_design_spacing_px(cd: &ColumnDef, dpi: f64) -> f64 {
if cd.column_count.max(1) <= 1 {
hwpunit_to_px(cd.spacing as i32, dpi)
} else {
0.0
}
}
fn page_holds_only_fresh_table_continuation(st: &TypesetState, paragraphs: &[Paragraph]) -> bool {
const FRESH_CONTINUATION_PAGE_MAX_FILL_RATIO: f64 = 0.30;
if st.current_items.is_empty() {
return false;
}
if st.current_height > st.available_height() * FRESH_CONTINUATION_PAGE_MAX_FILL_RATIO {
return false;
}
let mut has_continuation = false;
for item in &st.current_items {
match item {
PageItem::PartialTable {
is_continuation, ..
} if *is_continuation => has_continuation = true,
PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. } => {
let empty_only = paragraphs
.get(*para_index)
.is_some_and(|p| p.text.trim().is_empty() && p.controls.is_empty());
if !empty_only {
return false;
}
}
_ => return false,
}
}
has_continuation
}
fn para_has_visible_text(para: &Paragraph) -> bool {
para.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}')
}
fn para_has_non_whitespace_text(para: &Paragraph) -> bool {
para.text
.chars()
.any(|c| c > '\u{001F}' && c != '\u{FFFC}' && !c.is_whitespace())
|| crate::renderer::is_unstored_whitespace_object_host(para)
}
fn take_strict_plain_text_fit_after_empty_host_float_once(
pending: &mut bool,
para: &Paragraph,
) -> bool {
if !*pending || !para_has_non_whitespace_text(para) || !para.controls.is_empty() {
return false;
}
*pending = false;
true
}
fn paragraph_page_end_fit_height(
total_height: f64,
height_for_fit: f64,
require_full_advance: bool,
) -> f64 {
if require_full_advance {
total_height.max(height_for_fit)
} else {
height_for_fit
}
}
fn para_line_spacing_px(para: &Paragraph, dpi: f64) -> f64 {
para.line_segs
.last()
.filter(|seg| seg.line_spacing > 0)
.map(|seg| hwpunit_to_px(seg.line_spacing, dpi))
.unwrap_or(0.0)
}
fn has_following_non_positive_visible_float(para: &Paragraph, control_index: usize) -> bool {
para.controls
.iter()
.skip(control_index + 1)
.any(|ctrl| match ctrl {
Control::Table(table) => {
is_para_topbottom_float(&table.common)
&& signed_hwpunit(table.common.vertical_offset) <= 0
}
_ => false,
})
}
fn para_is_non_tac_overlay_table_anchor(para: &Paragraph) -> bool {
!para_has_non_whitespace_text(para)
&& para.controls.iter().any(|ctrl| {
matches!(
ctrl,
Control::Table(table)
if !table.common.treat_as_char
&& matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::InFrontOfText
| crate::model::shape::TextWrap::BehindText
)
)
})
}
fn para_is_empty_topbottom_table_anchor(para: &Paragraph) -> bool {
!para_has_visible_text(para)
&& para
.controls
.iter()
.any(|ctrl| matches!(ctrl, Control::Table(t) if is_para_topbottom_float(&t.common)))
}
fn native_hwp5_figure_table_overlay_guide_empty(
para_idx: usize,
para: &Paragraph,
paragraphs: &[Paragraph],
) -> bool {
if para.controls.is_empty()
&& !para_has_visible_text(para)
&& para.column_type == ColumnBreakType::None
{
let Some(guide_vpos) = para
.line_segs
.iter()
.find(|seg| !is_synthetic_line_seg(seg))
.map(|seg| seg.vertical_pos)
else {
return false;
};
let Some((_, host)) = (0..para_idx).rev().find_map(|idx| {
let candidate = paragraphs.get(idx)?;
(!candidate.controls.is_empty() || para_has_visible_text(candidate))
.then_some((idx, candidate))
}) else {
return false;
};
if host.para_shape_id != para.para_shape_id || para_has_visible_text(host) {
return false;
}
let Some((anchor_vpos, table)) = host
.line_segs
.iter()
.find(|seg| !is_synthetic_line_seg(seg))
.map(|seg| seg.vertical_pos)
.and_then(|anchor_vpos| {
host.controls.iter().find_map(|control| match control {
Control::Table(table)
if !table.common.treat_as_char
&& is_para_topbottom_float(&table.common)
&& matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
&& table.row_count == 2
&& table.col_count == 1
&& table.cells.len() == 2
&& signed_hwpunit(table.common.vertical_offset) > 0
&& table.cells.first().is_some_and(|cell| {
cell.paragraphs.iter().any(|cell_para| {
cell_para.controls.iter().any(|control| {
matches!(control, Control::Picture(_) | Control::Shape(_))
})
})
}) =>
{
Some((anchor_vpos, table))
}
_ => None,
})
})
else {
return false;
};
let table_bottom = anchor_vpos
.saturating_add(signed_hwpunit(table.common.vertical_offset).max(0))
.saturating_add(table.common.height.min(i32::MAX as u32) as i32);
return guide_vpos >= anchor_vpos && guide_vpos < table_bottom;
}
false
}
fn para_is_empty_tac_table_anchor(para: &Paragraph) -> bool {
!para_has_visible_text(para)
&& para
.controls
.iter()
.any(|ctrl| matches!(ctrl, Control::Table(t) if t.common.treat_as_char))
}
fn para_has_visible_text_or_equation(para: &Paragraph) -> bool {
para_has_visible_text(para)
|| para
.controls
.iter()
.any(|c| matches!(c, Control::Equation(eq) if eq.common.treat_as_char))
}
fn para_has_visible_text_and_treat_as_char_equation(para: &Paragraph) -> bool {
para_has_visible_text(para)
&& para
.controls
.iter()
.any(|c| matches!(c, Control::Equation(eq) if eq.common.treat_as_char))
}
fn para_is_short_auto_endnote_marker(para: &Paragraph) -> bool {
para.text
.chars()
.filter(|c| *c > '\u{001F}' && *c != '\u{FFFC}' && !c.is_whitespace())
.count()
<= 1
&& para.controls.iter().any(|control| {
matches!(
control,
Control::AutoNumber(number)
if number.number_type == crate::model::control::AutoNumberType::Endnote
)
})
}
fn is_treat_as_char_equation_control(ctrl: Option<&Control>) -> bool {
matches!(ctrl, Some(Control::Equation(eq)) if eq.common.treat_as_char)
}
fn para_is_treat_as_char_picture_only(para: &Paragraph) -> bool {
!para_has_visible_text(para)
&& para.controls.iter().any(|ctrl| match ctrl {
Control::Picture(pic) => pic.common.treat_as_char,
Control::Shape(shape) => shape.common().treat_as_char,
_ => false,
})
}
fn para_has_only_treat_as_char_picture_or_shape(para: &Paragraph) -> bool {
!para_has_visible_text(para)
&& !para.controls.is_empty()
&& para.controls.iter().all(|ctrl| match ctrl {
Control::Picture(pic) => pic.common.treat_as_char,
Control::Shape(shape) => shape.common().treat_as_char,
_ => false,
})
}
fn para_has_treat_as_char_picture_or_shape(para: &Paragraph) -> bool {
para.controls.iter().any(|ctrl| match ctrl {
Control::Picture(pic) => pic.common.treat_as_char,
Control::Shape(shape) => shape.common().treat_as_char,
_ => false,
})
}
fn hwp5_tac_prefix_has_owned_object_line(para: &Paragraph, table_line: usize) -> bool {
para.controls.iter().enumerate().any(|(index, control)| {
let is_tac_object = match control {
Control::Picture(picture) => picture.common.treat_as_char,
Control::Shape(shape) => shape.common().treat_as_char,
_ => false,
};
is_tac_object
&& crate::renderer::layout::control_line_seg_index(para, index)
.is_some_and(|line| line < table_line)
})
}
fn non_tac_picture_or_shape_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
match ctrl {
Control::Picture(pic) if !pic.common.treat_as_char => Some(&pic.common),
Control::Shape(shape) if !shape.common().treat_as_char => Some(shape.common()),
_ => None,
}
}
fn para_has_non_tac_picture_or_shape(para: &Paragraph) -> bool {
para.controls
.iter()
.any(|ctrl| non_tac_picture_or_shape_common(ctrl).is_some())
}
fn paper_overlay_object_bottom_abs_px(para: &Paragraph, dpi: f64) -> Option<f64> {
if !crate::renderer::layout::para_is_floating_overlay_anchor(para) {
return None;
}
let mut max_bottom: Option<f64> = None;
for ctrl in ¶.controls {
let common = match ctrl {
Control::Shape(shape) if !shape.common().treat_as_char => shape.common(),
Control::Picture(pic) if !pic.common.treat_as_char => &pic.common,
Control::Table(table) if !table.common.treat_as_char => &table.common,
_ => continue,
};
if !matches!(common.vert_rel_to, crate::model::shape::VertRelTo::Paper) {
continue;
}
let top_hu = signed_hwpunit(common.vertical_offset);
let bottom_hu = top_hu
.saturating_add(common.height as i32)
.saturating_add(common.margin.bottom as i32);
let bottom_px = hwpunit_to_px(bottom_hu, dpi);
max_bottom = Some(max_bottom.map_or(bottom_px, |prev| prev.max(bottom_px)));
}
max_bottom
}
fn para_is_columndef_only_separator(para: &Paragraph) -> bool {
para.text.trim().is_empty()
&& !para.controls.is_empty()
&& para
.controls
.iter()
.all(|c| matches!(c, Control::ColumnDef(_)))
}
fn para_is_paper_page_square_empty_table_anchor(para: &Paragraph) -> bool {
!para_has_visible_text(para)
&& para.controls.iter().any(|ctrl| {
matches!(ctrl, Control::Table(table)
if !table.common.treat_as_char
&& matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::Square
)
&& matches!(
table.common.vert_rel_to,
crate::model::shape::VertRelTo::Paper
| crate::model::shape::VertRelTo::Page
))
})
}
fn para_is_pre_paper_page_square_table_scaffold(para_idx: usize, paragraphs: &[Paragraph]) -> bool {
let Some(para) = paragraphs.get(para_idx) else {
return false;
};
if para_has_visible_text(para)
|| !matches!(
para.column_type,
ColumnBreakType::Page | ColumnBreakType::Section
)
|| !para.controls.iter().all(|ctrl| {
matches!(
ctrl,
Control::SectionDef(_) | Control::ColumnDef(_) | Control::Bookmark(_)
)
})
{
return false;
}
let Some(next) = paragraphs
.get(para_idx + 1)
.filter(|next| para_is_paper_page_square_empty_table_anchor(next))
else {
return false;
};
!matches!(
(para.line_segs.last(), next.line_segs.first()),
(Some(own), Some(following))
if own.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& following.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& following.vertical_pos > own.vertical_pos
)
}
fn para_is_post_paper_page_square_table_scaffold(
para_idx: usize,
paragraphs: &[Paragraph],
) -> bool {
let Some(para) = paragraphs.get(para_idx) else {
return false;
};
if para_has_visible_text(para) {
return false;
}
let empty_no_control_para =
para.column_type == ColumnBreakType::None && para.controls.is_empty();
let columndef_only_separator =
para.column_type == ColumnBreakType::Column && para_is_columndef_only_separator(para);
if !empty_no_control_para && !columndef_only_separator {
return false;
}
paragraphs
.get(para_idx.saturating_sub(1))
.is_some_and(para_is_paper_page_square_empty_table_anchor)
&& paragraphs
.get(para_idx + 1)
.is_some_and(para_has_visible_text)
}
fn columndef_separator_between_floating_overlays(
para_idx: usize,
paragraphs: &[Paragraph],
) -> bool {
let prev_overlay = (0..para_idx).rev().find_map(|idx| {
let para = paragraphs.get(idx)?;
if para.text.trim().is_empty()
&& (para.controls.is_empty() || para_is_columndef_only_separator(para))
{
return None;
}
Some(crate::renderer::layout::para_is_floating_overlay_anchor(
para,
))
});
let next_overlay = paragraphs.iter().skip(para_idx + 1).find_map(|para| {
if para.text.trim().is_empty()
&& (para.controls.is_empty() || para_is_columndef_only_separator(para))
{
return None;
}
Some(crate::renderer::layout::para_is_floating_overlay_anchor(
para,
))
});
prev_overlay == Some(true) && next_overlay == Some(true)
}
fn non_tac_picture_or_shape_block_height_px(para: &Paragraph, dpi: f64) -> Option<f64> {
let mut max_height = 0.0f64;
let mut found = false;
for ctrl in ¶.controls {
let Some(common) = non_tac_picture_or_shape_common(ctrl) else {
continue;
};
let block_height_hu =
common.height as i32 + common.margin.top as i32 + common.margin.bottom as i32;
max_height = max_height.max(hwpunit_to_px(block_height_hu.max(1), dpi));
found = true;
}
found.then_some(max_height)
}
fn non_tac_picture_or_shape_content_height_px(para: &Paragraph, dpi: f64) -> Option<f64> {
let mut max_height = 0.0f64;
let mut found = false;
for ctrl in ¶.controls {
let Some(common) = non_tac_picture_or_shape_common(ctrl) else {
continue;
};
max_height = max_height.max(hwpunit_to_px((common.height as i32).max(1), dpi));
found = true;
}
found.then_some(max_height)
}
fn non_tac_square_picture_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
let common = match ctrl {
Control::Picture(pic) => Some(&pic.common),
Control::Shape(shape) => {
if let crate::model::shape::ShapeObject::Picture(pic) = shape.as_ref() {
Some(&pic.common)
} else {
None
}
}
_ => None,
}?;
(!common.treat_as_char && matches!(common.text_wrap, crate::model::shape::TextWrap::Square))
.then_some(common)
}
fn non_tac_square_float_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
let common = match ctrl {
Control::Picture(pic) => Some(&pic.common),
Control::Shape(shape) => Some(shape.common()),
_ => None,
}?;
(!common.treat_as_char && matches!(common.text_wrap, crate::model::shape::TextWrap::Square))
.then_some(common)
}
fn square_float_left_lane_width(para: &Paragraph, col_w_hu: i32) -> Option<i32> {
use crate::model::shape::HorzRelTo;
let mut floats = para.controls.iter().filter_map(non_tac_square_float_common);
let common = floats.next()?;
if floats.next().is_some() {
return None;
}
if !matches!(common.horz_rel_to, HorzRelTo::Para | HorzRelTo::Column) {
return None;
}
let lane = common.horizontal_offset as i32;
let right_edge = lane
.saturating_add(common.width as i32)
.saturating_add(common.margin.right as i32);
(lane > 0 && lane < col_w_hu && right_edge >= col_w_hu - 200).then_some(lane)
}
fn synth_square_wrap_rects(
para: &Paragraph,
anchor_col_x: f64,
flow_y: f64,
dpi: f64,
) -> Vec<(f64, f64, f64, f64)> {
para.controls
.iter()
.filter_map(non_tac_square_picture_common)
.filter_map(|cm| {
let w = crate::renderer::hwpunit_to_px(cm.width as i32, dpi);
let h = crate::renderer::hwpunit_to_px(cm.height as i32, dpi);
if w < 8.0 || h < 8.0 {
return None;
}
let ml = crate::renderer::hwpunit_to_px(cm.margin.left as i32, dpi);
let mr = crate::renderer::hwpunit_to_px(cm.margin.right as i32, dpi);
let mb = crate::renderer::hwpunit_to_px(cm.margin.bottom as i32, dpi);
let x0 = anchor_col_x
+ crate::renderer::hwpunit_to_px(signed_hwpunit(cm.horizontal_offset), dpi)
- ml;
let x1 = x0 + ml + w + mr;
let top = flow_y
+ crate::renderer::hwpunit_to_px(signed_hwpunit(cm.vertical_offset).max(0), dpi);
let bottom = top + h + mb;
Some((x0, x1, top, bottom))
})
.collect()
}
fn endnote_first_local_paras(
body_len: usize,
endnote_sources: &[EndnoteParaSource],
local_indices: &[(usize, usize)],
) -> std::sync::Arc<std::collections::HashSet<usize>> {
std::sync::Arc::new(
local_indices
.iter()
.filter(|(global, _)| {
global
.checked_sub(body_len)
.and_then(|local| endnote_sources.get(local))
.is_some_and(|src| src.note_para_index == 0)
})
.map(|(_, local)| *local)
.collect(),
)
}
fn paragraph_by_global_index<'a>(
body_paragraphs: &'a [Paragraph],
endnote_paragraphs: &'a [Paragraph],
para_index: usize,
) -> Option<&'a Paragraph> {
if para_index < body_paragraphs.len() {
body_paragraphs.get(para_index)
} else {
endnote_paragraphs.get(para_index - body_paragraphs.len())
}
}
fn page_item_para_index(item: &PageItem) -> Option<usize> {
match item {
PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => Some(*para_index),
PageItem::EndnoteSeparator { .. } => None,
}
}
pub(super) fn page_item_vpos_base(item: &PageItem, paragraphs: &[Paragraph]) -> Option<i32> {
match item {
PageItem::PartialParagraph {
para_index,
start_line,
..
} => paragraphs
.get(*para_index)
.and_then(|para| para.line_segs.get(*start_line))
.map(|seg| seg.vertical_pos),
PageItem::FullParagraph { para_index }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => paragraphs
.get(*para_index)
.and_then(|para| para.line_segs.first())
.map(|seg| seg.vertical_pos),
PageItem::EndnoteSeparator { .. } => None,
}
}
fn square_picture_wrap_anchor_for_para(
st: &TypesetState,
body_paragraphs: &[Paragraph],
para: &Paragraph,
page_def: &PageDef,
) -> Option<crate::renderer::pagination::WrapAnchorRef> {
if st.wrap_around_cs < 0 {
return None;
}
let para_cs = para.line_segs.first().map(|s| s.column_start).unwrap_or(0);
let para_sw = para
.line_segs
.first()
.map(|s| s.segment_width as i32)
.unwrap_or(0);
let is_empty_para = para
.text
.chars()
.all(|ch| ch.is_whitespace() || ch == '\r' || ch == '\n')
&& para.controls.is_empty();
let any_seg_matches = para.line_segs.iter().any(|s| {
s.column_start == st.wrap_around_cs && s.segment_width as i32 == st.wrap_around_sw
});
let body_w =
(page_def.width as i32) - (page_def.margin_left as i32) - (page_def.margin_right as i32);
let sw0_match = st.wrap_around_sw == 0 && is_empty_para && para_sw > 0 && para_sw < body_w / 2;
let anchor_para = paragraph_by_global_index(
body_paragraphs,
&st.endnote_paragraphs,
st.wrap_around_table_para,
)?;
let anchor_image_match = if st.wrap_around_cs == 0 {
let body_left = page_def.margin_left as i32;
let expected_cs_hu = anchor_para
.controls
.iter()
.find_map(|ctrl| {
non_tac_square_picture_common(ctrl).map(|common| {
common.horizontal_offset as i32
+ common.width as i32
+ 2 * common.margin.right as i32
- body_left
})
})
.unwrap_or(0);
expected_cs_hu > 0
&& (para_cs - expected_cs_hu).abs() < 200
&& para_sw > 0
&& para_cs + para_sw <= body_w + 200
} else {
false
};
let cs_only_match = st.wrap_around_any_seg && para_cs == st.wrap_around_cs && para_sw > 0;
let matched = (para_cs == st.wrap_around_cs && para_sw == st.wrap_around_sw)
|| (any_seg_matches && (is_empty_para || st.wrap_around_any_seg))
|| sw0_match
|| anchor_image_match
|| cs_only_match;
if !matched {
return None;
}
anchor_para
.controls
.iter()
.find_map(non_tac_square_picture_common)?;
Some(crate::renderer::pagination::WrapAnchorRef {
anchor_para_index: st.wrap_around_table_para,
anchor_cs: st.wrap_around_cs,
anchor_sw: st.wrap_around_sw,
band_y_range: None,
})
}
fn maybe_register_square_picture_wrap_anchor(
st: &mut TypesetState,
body_paragraphs: &[Paragraph],
para: &Paragraph,
para_index: usize,
page_def: &PageDef,
) {
if st.wrap_around_cs < 0 {
return;
}
if let Some(anchor) = square_picture_wrap_anchor_for_para(st, body_paragraphs, para, page_def) {
st.register_following_wrap_anchor(para_index, anchor);
} else {
st.finish_stored_wrap_matching();
st.close_square_band();
}
}
fn activate_square_picture_wrap_for_para(
st: &mut TypesetState,
para_index: usize,
para: &Paragraph,
) {
if !para
.controls
.iter()
.any(|ctrl| non_tac_square_picture_common(ctrl).is_some())
{
return;
}
let anchor_cs = para.line_segs.first().map(|s| s.column_start).unwrap_or(0);
let anchor_sw = para
.line_segs
.first()
.map(|s| s.segment_width as i32)
.unwrap_or(0);
if anchor_cs > 0 || anchor_sw > 0 {
st.arm_control_wrap(anchor_cs, anchor_sw, para_index, true);
}
}
fn line_has_strict_equation_tac_control(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> bool {
let Some(line) = comp.lines.get(line_idx) else {
return false;
};
let start = line.char_start;
let end = composed_line_char_end(comp, line_idx);
end > start
&& comp.tac_controls.iter().any(|(pos, _, ci)| {
*pos >= start && *pos < end && is_treat_as_char_equation_control(para.controls.get(*ci))
})
}
fn line_is_leading_empty_equation_tac_guide(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> bool {
let Some(line) = comp.lines.get(line_idx) else {
return false;
};
let Some(next) = comp.lines.get(line_idx + 1) else {
return false;
};
line.runs.is_empty()
&& line.char_start == next.char_start
&& !line_has_strict_tac_control(comp, line_idx)
&& line_has_strict_equation_tac_control(para, comp, line_idx + 1)
}
fn equation_only_tac_line_assignment(
para: &Paragraph,
comp: &ComposedParagraph,
) -> Option<Vec<usize>> {
match equation_only_tac_line_assignment_with_storage(para, comp, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn equation_only_tac_line_assignment_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
comp: &ComposedParagraph,
storage: &S,
) -> Result<Option<Vec<usize>>, S::Error> {
let n_lines = comp.lines.len();
if n_lines <= 1 || comp.tac_controls.is_empty() {
return Ok(None);
}
if !comp.lines.iter().all(|line| line.runs.is_empty()) {
return Ok(None);
}
let degenerate = comp
.lines
.windows(2)
.any(|w| w[1].char_start <= w[0].char_start);
if !degenerate {
return Ok(None);
}
let mut assign = storage.filled(comp.tac_controls.len(), n_lines - 1)?;
let mut line_idx = 0usize;
let mut tac_idx = 0usize;
while tac_idx < comp.tac_controls.len() {
let pos = comp.tac_controls[tac_idx].0;
while line_idx < n_lines && comp.lines[line_idx].char_start < pos {
line_idx += 1;
}
let tac_start = tac_idx;
while tac_idx < comp.tac_controls.len() && comp.tac_controls[tac_idx].0 == pos {
tac_idx += 1;
}
let tac_count = tac_idx - tac_start;
let line_start = line_idx;
while line_idx < n_lines && comp.lines[line_idx].char_start == pos {
line_idx += 1;
}
let line_candidates: Vec<usize> = storage.collect(line_start..line_idx)?;
let filtered_candidates: Vec<usize> = storage.collect(
line_candidates
.iter()
.copied()
.filter(|idx| !line_is_leading_empty_equation_tac_guide(para, comp, *idx)),
)?;
let line_targets = if tac_count > 1 && line_candidates.len() >= tac_count {
&line_candidates
} else if filtered_candidates.is_empty() {
&line_candidates
} else {
&filtered_candidates
};
for offset in 0..tac_count {
assign[tac_start + offset] = if line_targets.is_empty() {
line_start.min(n_lines - 1)
} else {
line_targets[offset.min(line_targets.len() - 1)]
};
}
}
Ok(Some(assign))
}
fn tac_control_indices_for_line(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> Vec<usize> {
match tac_control_indices_for_line_with_storage(
para,
comp,
line_idx,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn tac_control_indices_for_line_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
storage: &S,
) -> Result<Vec<usize>, S::Error> {
let Some(line) = comp.lines.get(line_idx) else {
return Ok(Vec::new());
};
if comp.tac_controls.is_empty() {
return Ok(Vec::new());
}
if let Some(assign) =
crate::renderer::composer::composed_tac_line_assignment_with_storage(para, comp, storage)?
{
return storage.collect(
assign
.into_iter()
.filter_map(|(ci, owner)| (owner == line_idx).then_some(ci)),
);
}
if let Some(assign) = equation_only_tac_line_assignment_with_storage(para, comp, storage)? {
return storage.collect(comp.tac_controls.iter().enumerate().filter_map(
|(idx, (_, _, ci))| (assign.get(idx).copied() == Some(line_idx)).then_some(*ci),
));
}
if line.runs.is_empty() {
let start = line.char_start;
let end = comp
.lines
.get(line_idx + 1)
.map(|next| next.char_start)
.unwrap_or(usize::MAX);
return storage.collect(
comp.tac_controls
.iter()
.filter_map(|(pos, _, ci)| (*pos >= start && *pos < end).then_some(*ci)),
);
}
let next_start = comp.lines.get(line_idx + 1).map(|next| next.char_start);
let mut hits = Vec::new();
let mut run_start = line.char_start;
for (run_idx, run) in line.runs.iter().enumerate() {
let run_len = run.text.chars().count();
let run_end = run_start + run_len;
let next_line_starts_at_run_end = next_start.is_some_and(|start| start == run_end);
let allow_end_tac = run_idx == line.runs.len() - 1 && !next_line_starts_at_run_end;
for (pos, _, ci) in &comp.tac_controls {
if *pos >= run_start && (*pos < run_end || (allow_end_tac && *pos == run_end)) {
storage.push(&mut hits, *ci)?;
}
}
run_start = run_end;
}
Ok(hits)
}
fn line_has_tac_equation_control(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> bool {
tac_control_indices_for_line(para, comp, line_idx)
.iter()
.any(|ci| is_treat_as_char_equation_control(para.controls.get(*ci)))
}
fn line_leading_tac_equation_count(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> usize {
let Some(line_start) = comp.lines.get(line_idx).map(|line| line.char_start) else {
return 0;
};
let line_controls = tac_control_indices_for_line(para, comp, line_idx);
comp.tac_controls
.iter()
.filter(|(pos, _, ci)| {
*pos == line_start
&& line_controls.contains(ci)
&& is_treat_as_char_equation_control(para.controls.get(*ci))
})
.count()
}
fn line_is_equation_tac_text_run_only(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> bool {
if line_has_visible_text(comp, line_idx) {
return false;
}
let line_controls = tac_control_indices_for_line(para, comp, line_idx);
!line_controls.is_empty()
&& line_controls
.iter()
.all(|ci| is_treat_as_char_equation_control(para.controls.get(*ci)))
}
fn line_has_visible_text_or_tac_equation(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
) -> bool {
line_has_visible_text(comp, line_idx) || line_has_tac_equation_control(para, comp, line_idx)
}
fn line_has_tac_control(para: &Paragraph, comp: &ComposedParagraph, line_idx: usize) -> bool {
match line_has_tac_control_with_storage(para, comp, line_idx, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn line_has_tac_control_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
storage: &S,
) -> Result<bool, S::Error> {
Ok(!tac_control_indices_for_line_with_storage(para, comp, line_idx, storage)?.is_empty())
}
fn line_tac_picture_or_shape_height(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
dpi: f64,
) -> Option<f64> {
match line_tac_picture_or_shape_height_with_storage(
para,
comp,
line_idx,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn line_tac_picture_or_shape_height_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
dpi: f64,
storage: &S,
) -> Result<Option<f64>, S::Error> {
Ok(
tac_control_indices_for_line_with_storage(para, comp, line_idx, storage)?
.iter()
.find_map(|ci| {
para.controls
.get(*ci)
.and_then(|ctrl| crate::renderer::tac_object_flow_height_px(ctrl, dpi))
}),
)
}
fn text_line_is_picture_lead_in(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
raw_lh: f64,
max_fs: f64,
dpi: f64,
) -> bool {
match text_line_is_picture_lead_in_with_storage(
para,
comp,
line_idx,
raw_lh,
max_fs,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn text_line_is_picture_lead_in_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
comp: &ComposedParagraph,
line_idx: usize,
raw_lh: f64,
max_fs: f64,
dpi: f64,
storage: &S,
) -> Result<bool, S::Error> {
if max_fs <= 0.0 || raw_lh <= max_fs * 2.0 {
return Ok(false);
}
let Some(line) = comp.lines.get(line_idx) else {
return Ok(false);
};
if line.runs.iter().all(|run| run.text.trim().is_empty())
|| line_tac_picture_or_shape_height_with_storage(para, comp, line_idx, dpi, storage)?
.is_some()
{
return Ok(false);
}
let Some(next) = comp.lines.get(line_idx + 1) else {
return Ok(false);
};
if !next.runs.iter().all(|run| run.text.trim().is_empty()) {
return Ok(false);
}
Ok(
line_tac_picture_or_shape_height_with_storage(para, comp, line_idx + 1, dpi, storage)?
.map(|height| (raw_lh - height).abs() <= 8.0)
.unwrap_or(false),
)
}
fn native_hwp5_text_reset_before_large_tac_topbottom_picture_break_line(
st: &TypesetState,
para: &Paragraph,
fmt: &FormattedParagraph,
paragraphs: &[Paragraph],
para_idx: usize,
dpi: f64,
) -> Option<usize> {
if !st.profile.hwp5_stored_pagination_layout()
|| st.col_count != 1
|| st.current_footnote_height > 0.0
|| st.current_items.is_empty()
|| st.current_height < st.layout.body_area.height * 0.60
|| !para.controls.is_empty()
|| !para_has_visible_text(para)
|| fmt.line_heights.len() < 2
|| para.line_segs.len() < fmt.line_heights.len()
{
return None;
}
let next_para = paragraphs.get(para_idx + 1)?;
if next_para.controls.len() != 1
|| next_para.line_segs.len() != 1
|| para_has_visible_text(next_para)
|| !para_controls_only_tac_topbottom_objects(next_para)
{
return None;
}
let next_line = next_para.line_segs.first()?;
if is_synthetic_line_seg(next_line)
|| !(0..=8_000).contains(&next_line.vertical_pos)
|| hwpunit_to_px(next_line.line_height, dpi) < st.layout.body_area.height * 0.15
{
return None;
}
para.line_segs[..fmt.line_heights.len()]
.windows(2)
.enumerate()
.find_map(|(prev_idx, pair)| {
let (prev, next) = (&pair[0], &pair[1]);
if is_synthetic_line_seg(prev)
|| is_synthetic_line_seg(next)
|| prev.vertical_pos <= 0
|| next.vertical_pos != 0
{
return None;
}
(hwpunit_to_px(prev.vertical_pos.saturating_add(prev.line_height), dpi)
>= st.layout.body_area.height * 0.70)
.then_some(prev_idx + 1)
})
}
fn is_two_row_picture_caption_rowbreak_table(table: &crate::model::table::Table) -> bool {
if table.row_count != 2
|| table.col_count != 1
|| table.cells.len() != 2
|| table
.cells
.iter()
.any(|cell| cell.col != 0 || cell.row > 1 || cell.row_span != 1 || cell.col_span != 1)
{
return false;
}
let has_picture = table.cells.iter().any(|cell| {
cell.row == 0
&& cell.paragraphs.iter().any(|para| {
para.controls
.iter()
.any(|control| matches!(control, Control::Picture(_)))
})
});
let has_caption_text = table
.cells
.iter()
.any(|cell| cell.row == 1 && cell.paragraphs.iter().any(para_has_visible_text));
has_picture && has_caption_text
}
fn is_single_noninline_picture_table(table: &crate::model::table::Table) -> bool {
if table.common.treat_as_char
|| table.row_count != 1
|| table.col_count != 1
|| table.cells.len() != 1
|| !matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
{
return false;
}
let Some(cell) = table.cells.first() else {
return false;
};
cell.row == 0
&& cell.col == 0
&& cell.row_span == 1
&& cell.col_span == 1
&& cell.paragraphs.len() == 1
&& cell.paragraphs.first().is_some_and(|cell_para| {
cell_para.text.trim().is_empty()
&& cell_para.controls.len() == 1
&& matches!(
cell_para.controls.first(),
Some(Control::Picture(picture)) if !picture.common.treat_as_char
)
})
}
use crate::renderer::stored_float_anchor::{
stored_ladder_leaves_object_room, stored_single_topbottom_top_px,
};
fn is_stored_anchor_picture_table(table: &crate::model::table::Table) -> bool {
!table.common.treat_as_char
&& matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
&& (is_single_noninline_picture_table(table)
|| is_two_row_picture_caption_rowbreak_table(table))
}
fn is_single_rowbreak_table_with_trustworthy_declared_height(
table: &crate::model::table::Table,
effective_height: f64,
dpi: f64,
) -> bool {
if table.common.treat_as_char
|| table.row_count != 1
|| table.col_count != 1
|| table.cells.len() != 1
|| !matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
{
return false;
}
let Some(cell) = table.cells.first() else {
return false;
};
if cell.row != 0 || cell.col != 0 || cell.row_span != 1 || cell.col_span != 1 {
return false;
}
let declared_height = hwpunit_to_px(table.common.height as i32, dpi).max(0.0);
declared_height > 0.0
&& effective_height <= declared_height * SINGLE_ROW_DECLARED_TRUST_MAX_RATIO
}
fn rowbreak_row_has_internal_saved_vpos_reset(
table: &crate::model::table::Table,
row: usize,
) -> bool {
table
.cells
.iter()
.filter(|cell| cell.row as usize == row)
.any(cell_has_internal_saved_vpos_reset)
}
fn cell_has_internal_saved_vpos_reset(cell: &crate::model::table::Cell) -> bool {
let mut previous_vpos = None;
for para in &cell.paragraphs {
for seg in para
.line_segs
.iter()
.filter(|seg| !is_synthetic_line_seg(seg))
{
if previous_vpos.is_some_and(|previous| previous > 0 && seg.vertical_pos <= 0) {
return true;
}
previous_vpos = Some(seg.vertical_pos);
}
}
false
}
pub(in crate::renderer) fn none_table_is_atomic_here(table: &crate::model::table::Table) -> bool {
matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::None
) && !(!table.common.treat_as_char
&& is_para_topbottom_float(&table.common)
&& signed_hwpunit(table.common.vertical_offset) > 0)
}
pub(in crate::renderer) fn cell_unit_row_is_atomic_here(
table: &crate::model::table::Table,
) -> bool {
matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::CellBreak
)
}
fn rowbreak_table_has_internal_saved_vpos_reset(table: &crate::model::table::Table) -> bool {
let row_count = table.row_count as usize;
table
.cells
.iter()
.any(|cell| (cell.row as usize) < row_count && cell_has_internal_saved_vpos_reset(cell))
}
pub(crate) fn missing_lineseg_trailing_line_break(
para: &Paragraph,
line_count: usize,
current_height: f64,
available: f64,
trailing_line_spacing: f64,
source_uses_inline_field_reset: bool,
hwp3_converted_missing_lineseg: bool,
) -> Option<usize> {
crate::renderer::pagination::missing_lineseg_fragment_boundary(
para,
line_count,
current_height,
available,
trailing_line_spacing,
source_uses_inline_field_reset,
hwp3_converted_missing_lineseg,
)
}
fn is_synthetic_line_seg(ls: &LineSeg) -> bool {
ls.tag & 0x80000000 != 0
}
fn hwpx_stored_tac_table_starts_at_page_top(
para: &Paragraph,
table: &crate::model::table::Table,
current_items_empty: bool,
current_height: f64,
body_available: f64,
dpi: f64,
) -> bool {
if current_items_empty || current_height < 1.0 || !table.common.treat_as_char {
return false;
}
let segs: Vec<&LineSeg> = para
.line_segs
.iter()
.filter(|seg| !is_synthetic_line_seg(seg))
.collect();
let Some(seg) = segs.first() else {
return false;
};
if segs.len() != 1 {
return false;
}
let stored_h = hwpunit_to_px(seg.line_height, dpi);
stored_h >= body_available * 0.5 && current_height + stored_h > body_available
}
const NEAR_TOP_RESET_EMPTY_PAGE_FILL_RATIO: f64 = 0.10;
fn near_top_reset_page_is_barely_started(current_height: f64, available_height: f64) -> bool {
available_height > 0.0
&& current_height <= available_height * NEAR_TOP_RESET_EMPTY_PAGE_FILL_RATIO
}
fn native_near_top_reset_exceeds_remaining(
para: &Paragraph,
para_sb_hu: i32,
current_height: f64,
available_height: f64,
dpi: f64,
) -> bool {
let remaining = (available_height - current_height).max(0.0);
let real_lines: Vec<&LineSeg> = para
.line_segs
.iter()
.filter(|ls| !is_synthetic_line_seg(ls))
.collect();
if real_lines.is_empty() {
return true;
}
let sb_px = hwpunit_to_px(para_sb_hu.max(0), dpi);
let lines_px: f64 = real_lines
.iter()
.map(|ls| hwpunit_to_px(ls.line_height.max(0), dpi))
.sum();
sb_px + lines_px > remaining + 0.5
}
fn para_has_floating_object(para: &Paragraph) -> bool {
para.controls.iter().any(|c| {
matches!(
c,
Control::Shape(_) | Control::Table(_) | Control::Picture(_) | Control::Equation(_)
) && !c.is_treat_as_char_object()
})
}
fn stored_vpos_top_collision(prev: &Paragraph, curr: &Paragraph) -> bool {
if para_has_floating_object(prev) || para_has_floating_object(curr) {
return false;
}
if para_has_visible_text(prev) || para_has_visible_text(curr) || prev.controls.is_empty() {
return false;
}
let real = |ls: &&LineSeg| !is_synthetic_line_seg(ls);
let (Some(prev_first), Some(prev_last), Some(curr_first)) = (
prev.line_segs.iter().find(real),
prev.line_segs.iter().rev().find(real),
curr.line_segs.iter().find(real),
) else {
return false;
};
let parsed_seg = |ls: &LineSeg| {
ls.tag & LineSeg::TAG_FIRST_SEGMENT != 0 && ls.segment_width > 0 && ls.line_height > 0
};
if !parsed_seg(prev_first) || !parsed_seg(prev_last) || !parsed_seg(curr_first) {
return false;
}
if prev_last.line_height.saturating_add(prev_last.line_spacing) <= 0 {
return false;
}
prev_first.vertical_pos == 0
&& prev_last.vertical_pos == 0
&& curr_first.vertical_pos == 0
&& prev_last.column_start == curr_first.column_start
&& prev_last.segment_width == curr_first.segment_width
}
fn original_hwpx_tac_filled_page_keeps_short_trail(
original_hwpx: bool,
table: &crate::model::table::Table,
table_height_px: f64,
body_height_px: f64,
remaining_px: f64,
current_h: f64,
next_h: f64,
) -> bool {
use crate::model::shape::{HorzRelTo, TextWrap};
original_hwpx
&& table.common.treat_as_char
&& matches!(table.common.text_wrap, TextWrap::TopAndBottom)
&& matches!(table.common.horz_rel_to, HorzRelTo::Column)
&& table.row_count == 4
&& table.col_count == 1
&& body_height_px > 0.0
&& table_height_px >= body_height_px * 0.90
&& current_h > 0.0
&& next_h > 0.0
&& current_h < 40.0
&& next_h < 40.0
&& remaining_px + 0.5 >= current_h
&& remaining_px + 0.5 < current_h + next_h
}
fn saved_rowbreak_first_fragment_flow_overflow_allowance(
declared_height: u32,
outer_table_owns_row_geometry: bool,
source_flow_bottom: f64,
fragment_flow_bottom: f64,
) -> f64 {
const SOURCE_FRAME_EPSILON_PX: f64 = 0.5;
if declared_height == 0
|| declared_height > i32::MAX as u32
|| !outer_table_owns_row_geometry
|| !source_flow_bottom.is_finite()
|| !fragment_flow_bottom.is_finite()
|| source_flow_bottom <= 0.0
|| fragment_flow_bottom <= 0.0
|| source_flow_bottom > fragment_flow_bottom + SOURCE_FRAME_EPSILON_PX
{
return 0.0;
}
(fragment_flow_bottom - source_flow_bottom).max(0.0)
}
const SAVED_FRAME_ROW_END_STORED_TOLERANCE_PX: f64 = 1.0;
fn nearest_saved_rowbreak_frame_row_end(
frame_height: f64,
row_heights: &[f64],
stored_row_heights: &[f64],
cell_spacing: f64,
) -> Option<usize> {
if !frame_height.is_finite() || frame_height <= 0.0 {
return None;
}
let mut bottom = 0.0;
let mut nearest: Option<(usize, f64, f64)> = None;
for (row, height) in row_heights.iter().enumerate() {
if row > 0 {
bottom += cell_spacing;
}
bottom += height;
let distance = (bottom - frame_height).abs();
if nearest.is_none_or(|(_, best, _)| distance < best) {
nearest = Some((row + 1, distance, bottom));
}
}
let (end_row, _, row_bottom) = nearest?;
let shortfall = row_bottom - frame_height;
if shortfall <= 0.0 {
return Some(end_row);
}
let drift_budget: f64 = row_heights
.iter()
.take(end_row)
.enumerate()
.map(|(row, measured)| {
let stored = stored_row_heights.get(row).copied().unwrap_or(0.0);
if stored > 0.0 && stored.is_finite() {
(measured - stored).abs()
} else {
*measured
}
})
.sum::<f64>()
+ SAVED_FRAME_ROW_END_STORED_TOLERANCE_PX * end_row as f64;
(shortfall <= drift_budget.max(MIN_TOP_KEEP_PX)).then_some(end_row)
}
fn visible_host_is_numbered_table_caption(para: &Paragraph) -> bool {
let has_table_number_control = para.controls.iter().any(|control| {
matches!(
control,
Control::AutoNumber(number)
if number.number_type == crate::model::control::AutoNumberType::Table
) || matches!(
control,
Control::NewNumber(number)
if number.number_type == crate::model::control::AutoNumberType::Table
)
});
if has_table_number_control {
return true;
}
let text = para.text.trim_start();
let suffix = if let Some(rest) = text.strip_prefix('표') {
rest
} else if text
.get(.."Table".len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("Table"))
{
&text["Table".len()..]
} else {
return false;
};
suffix
.trim_start()
.chars()
.next()
.is_some_and(char::is_numeric)
}
fn native_hwp5_rowbreak_host_precedes_first_fragment(
para: &Paragraph,
table: &crate::model::table::Table,
) -> bool {
if !para_has_non_whitespace_text(para)
|| !visible_host_is_numbered_table_caption(para)
|| !is_para_topbottom_float(&table.common)
|| !matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
|| para
.controls
.iter()
.filter(|control| matches!(control, Control::Table(_)))
.count()
!= 1
{
return false;
}
let vertical_offset = signed_hwpunit(table.common.vertical_offset);
if vertical_offset <= 0 {
return false;
}
let mut stored = para
.line_segs
.iter()
.filter(|seg| !is_synthetic_line_seg(seg) && seg.line_height > 0);
let Some(first) = stored.next() else {
return false;
};
let last = stored.next_back().unwrap_or(first);
let stored_host_span = last
.vertical_pos
.saturating_sub(first.vertical_pos)
.saturating_add(last.line_height)
.max(0);
stored_host_span > 0 && stored_host_span <= vertical_offset
}
fn para_is_page_bottom_fixed_table_anchor(para: &Paragraph) -> bool {
!para_has_visible_text(para)
&& para
.controls
.iter()
.any(|c| matches!(c, Control::Table(t) if is_page_bottom_fixed_float(&t.common)))
}
fn para_controls_only_topbottom_floats(para: &Paragraph) -> bool {
!para.controls.is_empty()
&& para.controls.iter().all(|c| match c {
Control::Picture(p) => is_para_topbottom_float(&p.common),
Control::Shape(s) => is_para_topbottom_float(s.common()),
_ => false,
})
}
fn para_controls_only_tac_topbottom_objects(para: &Paragraph) -> bool {
use crate::model::shape::TextWrap;
!para.controls.is_empty()
&& para.controls.iter().all(|c| match c {
Control::Picture(p) => {
p.common.treat_as_char && matches!(p.common.text_wrap, TextWrap::TopAndBottom)
}
Control::Shape(s) => {
s.common().treat_as_char && matches!(s.common().text_wrap, TextWrap::TopAndBottom)
}
_ => false,
})
}
fn para_hosts_page_anchored_block(para: &Paragraph) -> bool {
use crate::model::shape::{TextWrap, VertRelTo};
let is_page_anchored_block = |common: &crate::model::shape::CommonObjAttr| {
!common.treat_as_char
&& matches!(common.vert_rel_to, VertRelTo::Page)
&& matches!(common.text_wrap, TextWrap::TopAndBottom)
};
para.controls.iter().any(|c| match c {
Control::Table(t) => is_page_anchored_block(&t.common),
Control::Picture(p) => is_page_anchored_block(&p.common),
Control::Shape(sh) => is_page_anchored_block(sh.common()),
_ => false,
})
}
fn paragraph_saved_vpos_reset_starts_new_page_after(
current_para: &Paragraph,
next_para: &Paragraph,
col_count: u16,
is_hwp3_variant: bool,
) -> bool {
if para_is_page_bottom_fixed_table_anchor(next_para) {
return false;
}
let next_first_vpos = next_para.line_segs.first().map(|s| s.vertical_pos);
let curr_last_vpos = if para_has_visible_text(current_para) {
current_para
.line_segs
.iter()
.rev()
.find(|s| !is_synthetic_line_seg(s))
.map(|s| s.vertical_pos)
} else {
current_para.line_segs.last().map(|s| s.vertical_pos)
};
let multi_col = col_count > 1;
let allowed_top_vpos = if is_hwp3_variant { 1500 } else { 0 };
matches!((next_first_vpos, curr_last_vpos), (Some(nv), Some(cl))
if (if multi_col { nv < cl } else { nv <= allowed_top_vpos }) && cl > 5000)
}
const LADDER_FIT_EPSILON_PX: f64 = 1.0;
const STORED_VPOS_REWIND_MIN_FILL: f64 = 0.90;
pub(in crate::renderer::typeset) fn stored_vpos_overflow_defers_paragraph(
para: &Paragraph,
next_para: Option<&Paragraph>,
body_bottom_px: f64,
dpi: f64,
) -> bool {
let first_stored = |p: &Paragraph| {
p.line_segs
.iter()
.find(|seg| !is_synthetic_line_seg(seg))
.map(|seg| seg.vertical_pos)
};
let (Some(own), Some(next)) = (first_stored(para), next_para.and_then(first_stored)) else {
return false;
};
let hosts_table = para
.controls
.iter()
.any(|c| matches!(c, crate::model::control::Control::Table(_)));
let own_px = hwpunit_to_px(own, dpi);
let overflows_body_narrowly =
own > 0 && own_px > body_bottom_px && own_px - body_bottom_px <= MIN_TOP_KEEP_PX;
hosts_table && overflows_body_narrowly && next < own
}
fn stored_vpos_rewinds(prev_vpos: Option<i32>, para: &Paragraph) -> bool {
stored_vpos_rewinds_after(prev_vpos.map(|vpos| (vpos, vpos)), para)
}
fn stored_vpos_rewinds_after(prev_line: Option<(i32, i32)>, para: &Paragraph) -> bool {
let Some(nv) = para
.line_segs
.iter()
.find(|s| !is_synthetic_line_seg(s))
.map(|s| s.vertical_pos)
else {
return false;
};
prev_line.is_some_and(|(start, bottom)| nv < start && start.max(bottom) > 5000)
}
fn stored_vpos_restarts_near_body_top(para: &Paragraph) -> bool {
para.line_segs
.iter()
.find(|s| !is_synthetic_line_seg(s))
.is_some_and(|s| s.vertical_pos <= 5000)
}
fn stored_rewind_boundary_matches_current_flow(
paragraphs: &[Paragraph],
para_idx: usize,
current_items: &[PageItem],
current_height_px: f64,
dpi: f64,
) -> bool {
let Some((owner, (stored_end_hu, advance_hu))) = paragraphs[..para_idx.min(paragraphs.len())]
.iter()
.enumerate()
.rev()
.find_map(|(owner, para)| {
paragraph::stored_lines::stored_tail_end_and_advance_hu(para).map(|tail| (owner, tail))
})
else {
return false;
};
if paragraphs[owner + 1..para_idx.min(paragraphs.len())]
.iter()
.any(|between| {
!between.line_segs.is_empty() && crate::renderer::para_has_no_stored_line_segs(between)
})
{
return false;
}
if !current_items
.iter()
.any(|item| page_item_para_index(item) == Some(owner))
{
return false;
}
let stored_end_px = hwpunit_to_px(stored_end_hu, dpi);
let tolerance_px = hwpunit_to_px(advance_hu.max(0), dpi) * 1.5;
(current_height_px - stored_end_px).abs() <= tolerance_px
}
fn preceding_stored_line_span(paragraphs: &[Paragraph], para_idx: usize) -> Option<(i32, i32)> {
paragraphs[..para_idx.min(paragraphs.len())]
.iter()
.rev()
.find_map(|p| {
p.line_segs
.iter()
.rev()
.find(|s| !is_synthetic_line_seg(s))
.map(|s| {
(
s.vertical_pos,
s.vertical_pos.saturating_add(s.line_height.max(0)),
)
})
})
}
fn preceding_stored_vpos(paragraphs: &[Paragraph], para_idx: usize) -> Option<i32> {
paragraphs[..para_idx.min(paragraphs.len())]
.iter()
.rev()
.find_map(|p| {
p.line_segs
.iter()
.rev()
.find(|s| !is_synthetic_line_seg(s))
.map(|s| s.vertical_pos)
})
}
fn stored_zero_vpos_after_near_full_line(
paragraphs: &[Paragraph],
para_idx: usize,
body_height_hu: i32,
) -> bool {
let current_starts_at_zero = paragraphs
.get(para_idx)
.and_then(|para| {
para.line_segs
.iter()
.find(|seg| !is_synthetic_line_seg(seg))
})
.is_some_and(|seg| seg.vertical_pos == 0);
if !current_starts_at_zero || body_height_hu <= 0 {
return false;
}
paragraphs[..para_idx.min(paragraphs.len())]
.iter()
.rev()
.find_map(|para| {
para.line_segs
.iter()
.rev()
.find(|seg| !is_synthetic_line_seg(seg))
})
.is_some_and(|seg| {
let bottom = seg.vertical_pos.saturating_add(seg.line_height);
bottom >= body_height_hu.saturating_mul(85) / 100
})
}
fn native_hwp5_saved_rowbreak_tail_frame_matches(
source_top: f64,
source_bottom: f64,
current_height: f64,
available: f64,
) -> bool {
const MIN_HOST_SPACING_DRIFT_PX: f64 = 1.0;
const MAX_HOST_SPACING_DRIFT_PX: f64 = 4.0;
const MAX_BODY_TAIL_GAP_PX: f64 = 8.0;
let host_spacing_drift = current_height - source_top;
let body_tail_gap = available - source_bottom;
host_spacing_drift >= MIN_HOST_SPACING_DRIFT_PX
&& host_spacing_drift <= MAX_HOST_SPACING_DRIFT_PX
&& body_tail_gap >= 0.0
&& body_tail_gap <= MAX_BODY_TAIL_GAP_PX
}
fn paragraph_forces_page_boundary_after(
current_para: &Paragraph,
next_para: &Paragraph,
col_count: u16,
is_hwp3_variant: bool,
) -> bool {
matches!(
next_para.column_type,
ColumnBreakType::Page | ColumnBreakType::Section
) || paragraph_saved_vpos_reset_starts_new_page_after(
current_para,
next_para,
col_count,
is_hwp3_variant,
)
}
fn empty_table_carrier_column_break_before_page_table(
para_idx: usize,
para: &Paragraph,
paragraphs: &[Paragraph],
) -> bool {
if para_idx == 0
|| para.column_type != ColumnBreakType::Column
|| !para.text.trim().is_empty()
|| !para.controls.is_empty()
{
return false;
}
let previous = ¶graphs[para_idx - 1];
let Some(next) = paragraphs.get(para_idx + 1) else {
return false;
};
matches!(previous.controls.as_slice(), [Control::Table(table)]
if !table.common.treat_as_char)
&& next.column_type == ColumnBreakType::Page
&& matches!(next.controls.as_slice(), [Control::Table(table)]
if !table.common.treat_as_char)
}
fn single_line_visible_bounds_px(
para: &Paragraph,
page_vpos_base: i32,
dpi: f64,
) -> Option<(f64, f64)> {
let mut real_lines = para
.line_segs
.iter()
.filter(|ls| !is_synthetic_line_seg(ls));
let line = real_lines.next()?;
if real_lines.next().is_some() {
return None;
}
line_seg_visible_bounds_px(line, page_vpos_base, dpi)
}
fn line_seg_visible_bounds_px(seg: &LineSeg, page_vpos_base: i32, dpi: f64) -> Option<(f64, f64)> {
let top = seg.vertical_pos.saturating_sub(page_vpos_base);
let bottom = seg
.vertical_pos
.saturating_add(seg.line_height)
.saturating_sub(page_vpos_base);
(top >= 0 && bottom >= 0).then(|| (hwpunit_to_px(top, dpi), hwpunit_to_px(bottom, dpi)))
}
const SAVED_TAIL_FIT_CHAIN_CAP: usize = 2;
#[derive(Debug, PartialEq, Eq)]
enum SavedTailFitChainDecision {
NoChange,
Advance,
Break,
}
fn saved_tail_fit_chain_decision(
tail_fit_chain: usize,
saved_tail_vpos_fit: bool,
hwp_authoritative: bool,
native_hwp5_reset_tail_fits_actual_footnote_boundary: bool,
) -> SavedTailFitChainDecision {
if !saved_tail_vpos_fit
|| hwp_authoritative
|| native_hwp5_reset_tail_fits_actual_footnote_boundary
{
SavedTailFitChainDecision::NoChange
} else if tail_fit_chain >= SAVED_TAIL_FIT_CHAIN_CAP {
SavedTailFitChainDecision::Break
} else {
SavedTailFitChainDecision::Advance
}
}
const SAVED_LINE_FLOW_ANCHOR_TOLERANCE_PX: f64 = 16.0;
const SAVED_FRAME_FLOW_DRIFT_TOLERANCE_PX: f64 = 64.0;
const BODY_BOTTOM_SEAT_PX: f64 = 10.0;
const TERMINAL_ROW_BOTTOM_SQUEEZE_TOLERANCE_PX: f64 = 13.0;
const TERMINAL_ROW_BOTTOM_SQUEEZE_MAX_REST_PX: f64 = 100.0;
const TERMINAL_ROW_BOTTOM_SQUEEZE_MIN_HEADROOM_PX: f64 = 12.0;
fn saved_bounds_overlap_current_flow(bounds: (f64, f64), current_height: f64) -> bool {
let (top, bottom) = bounds;
let line_height = (bottom - top).max(0.0);
line_height > 0.0 && top <= current_height + line_height && current_height <= bottom
}
fn saved_line_is_anchored_to_current_flow(bounds: (f64, f64), current_height: f64) -> bool {
let (top, bottom) = bounds;
bottom > top
&& top <= current_height
&& current_height <= top + SAVED_LINE_FLOW_ANCHOR_TOLERANCE_PX
}
fn saved_line_clears_footnote_area(
current_footnote_height: f64,
is_single_column: bool,
overflow: f64,
saved_bounds: Option<(f64, f64)>,
base_available_height: f64,
fragment_flow_top: f64,
line_flow_top: f64,
) -> bool {
current_footnote_height > 0.0
&& is_single_column
&& overflow <= 0.0
&& saved_bounds.is_some_and(|(top, bottom)| {
let text_limit = base_available_height - current_footnote_height;
top >= 0.0
&& top <= base_available_height
&& bottom <= text_limit
&& bottom > top
&& top <= line_flow_top.max(fragment_flow_top)
&& fragment_flow_top <= top + SAVED_LINE_FLOW_ANCHOR_TOLERANCE_PX
})
}
fn saved_bounds_fit_at_flow_tail(
bounds: (f64, f64),
current_height: f64,
available: f64,
bottom_spill: f64,
) -> bool {
saved_bounds_overlap_current_flow(bounds, current_height)
&& bounds.1 <= available + bottom_spill
}
fn saved_table_bounds_fit_at_flow_tail(
bounds: (f64, f64),
current_height: f64,
available: f64,
table_height: f64,
) -> bool {
let (top, _) = bounds;
let source_frame_leads_current_flow =
current_height <= top && saved_bounds_overlap_current_flow(bounds, current_height);
let current_flow_inside_source_frame = top > 0.0
&& top <= current_height
&& current_height <= top + SAVED_FRAME_FLOW_DRIFT_TOLERANCE_PX
&& current_height <= bounds.1;
table_height.is_finite()
&& table_height > 0.0
&& (saved_line_is_anchored_to_current_flow(bounds, current_height)
|| source_frame_leads_current_flow
|| current_flow_inside_source_frame)
&& bounds.1 <= available
&& bounds.0 + table_height <= available
}
pub(crate) fn stored_ladder_omits_tac_band(
charged_px: f64,
declared_px: f64,
measured_px: f64,
) -> bool {
declared_px > 1.0
&& measured_px > 1.0
&& declared_px.max(measured_px) < declared_px.min(measured_px) * 2.0
&& charged_px < declared_px.min(measured_px) * 0.25
}
fn stored_tac_table_frame_height(
table: &crate::model::table::Table,
dpi: f64,
measured_height: f64,
) -> f64 {
let declared_height = hwpunit_to_px(table.common.height.min(i32::MAX as u32) as i32, dpi);
if declared_height.is_finite() && declared_height > 0.0 {
declared_height
} else {
measured_height
}
}
#[cfg(test)]
mod saved_tac_table_flow_tail_contract {
use super::saved_table_bounds_fit_at_flow_tail;
#[test]
fn requires_the_table_object_not_just_its_anchor_line_to_fit() {
assert!(saved_table_bounds_fit_at_flow_tail(
(850.0, 870.0),
858.0,
971.0,
100.0,
));
assert!(
!saved_table_bounds_fit_at_flow_tail((850.0, 870.0), 858.0, 971.0, 889.0,),
"a tail anchor line cannot authorize a table that extends into the next page"
);
}
#[test]
fn accepts_a_forward_source_frame_that_overlaps_the_current_flow() {
assert!(saved_table_bounds_fit_at_flow_tail(
(120.0, 500.0),
100.0,
700.0,
350.0,
));
assert!(!saved_table_bounds_fit_at_flow_tail(
(0.0, 500.0),
400.0,
700.0,
350.0,
));
}
}
fn paragraph_saved_visible_bounds(
para: &Paragraph,
page_vpos_base: i32,
dpi: f64,
) -> Option<(f64, f64)> {
let mut bounds: Option<(f64, f64)> = None;
for seg in para
.line_segs
.iter()
.filter(|seg| !is_synthetic_line_seg(seg))
{
let (top, bottom) = line_seg_visible_bounds_px(seg, page_vpos_base, dpi)?;
bounds = Some(match bounds {
Some((min_top, max_bottom)) => (min_top.min(top), max_bottom.max(bottom)),
None => (top, bottom),
});
}
bounds
}
fn saved_line_range_fits_body_tail(
para: &Paragraph,
start_line: usize,
end_line: usize,
body_height_px: f64,
page_vpos_base: i32,
dpi: f64,
) -> bool {
if start_line >= end_line || end_line > para.line_segs.len() {
return false;
}
let mut prev_vpos: Option<i32> = None;
for seg in ¶.line_segs[start_line..end_line] {
if is_synthetic_line_seg(seg) || seg.vertical_pos <= 0 {
return false;
}
if prev_vpos.is_some_and(|prev| seg.vertical_pos < prev) {
return false;
}
let Some((_, bottom_px)) = line_seg_visible_bounds_px(seg, page_vpos_base, dpi) else {
return false;
};
if bottom_px > body_height_px + 0.5 {
return false;
}
prev_vpos = Some(seg.vertical_pos);
}
true
}
fn stored_body_reset_fragment_matches_current_flow(
st: &TypesetState,
para: &Paragraph,
start_line: usize,
break_line: usize,
current_page_vpos_base: i32,
spacing_before: f64,
dpi: f64,
) -> bool {
paragraph::scan::stored_body_reset_fragment_matches_current_flow(
&st.paragraph_line_scan_page(),
para,
start_line,
break_line,
current_page_vpos_base,
spacing_before,
dpi,
)
}
fn paragraph_text_looks_like_list_continuation_tail(para: &Paragraph) -> bool {
let text = para.text.trim_start();
text.starts_with('.') || text.starts_with('-') || text.starts_with('·') || text.starts_with('•')
}
fn saved_flow_marks_page_last(paragraphs: &[Paragraph], para_idx: usize) -> bool {
let curr_vpos = match paragraphs
.get(para_idx)
.and_then(|p| p.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)))
{
Some(ls) => ls.vertical_pos,
None => return false,
};
for next_para in paragraphs.iter().skip(para_idx + 1) {
if matches!(
next_para.column_type,
ColumnBreakType::Page | ColumnBreakType::Section
) {
return true;
}
if let Some(next) = next_para
.line_segs
.iter()
.find(|ls| !is_synthetic_line_seg(ls))
{
return next.vertical_pos < curr_vpos;
}
}
true
}
fn positive_vpos_end_before_negative_wrap(para: &Paragraph) -> Option<i32> {
let last_real = para
.line_segs
.iter()
.rev()
.find(|ls| !is_synthetic_line_seg(ls))?;
if last_real.vertical_pos >= 0 {
return None;
}
para.line_segs
.iter()
.filter(|ls| !is_synthetic_line_seg(ls) && ls.vertical_pos > 0)
.map(|ls| ls.vertical_pos.saturating_add(ls.line_height))
.max()
}
fn para_near_rowbreak_table(paragraphs: &[Paragraph], para_idx: usize) -> bool {
let start = para_idx.saturating_sub(1);
let end = (para_idx + 3).min(paragraphs.len());
paragraphs[start..end].iter().any(|para| {
para.controls.iter().any(|control| {
matches!(
control,
Control::Table(table)
if matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
)
})
})
}
fn section_has_zero_high_attr_rowbreak_table(paragraphs: &[Paragraph]) -> bool {
paragraphs.iter().any(|para| {
para.controls.iter().any(|control| {
matches!(
control,
Control::Table(table)
if matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
) && (table.raw_table_record_attr & 0xff00_0000) == 0
)
})
})
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct DumpFormattedParagraphHeight {
pub total: f64,
pub spacing_before: f64,
pub line_height_sum: f64,
pub spacing_after: f64,
pub line_spacing_sum: f64,
}
crate::storage::clone_copy!(DumpFormattedParagraphHeight);
mod controls;
#[path = "typeset/inline_flow.rs"]
mod inline_flow;
mod notes;
pub(crate) use notes::endnotes::content::endnote_first_para_render_offset;
mod paragraph;
mod section;
mod state;
mod stored_table_frame;
use state::TypesetState;
mod table;
pub(crate) use table::fit_measured_for_host;
fn ladder_spacing_omitted_signature(
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
dpi: f64,
) -> bool {
use crate::model::paragraph::LineSeg;
let mut text_paras = 0usize;
let mut segless_text_paras = 0usize;
for p in paragraphs {
if p.text.trim().is_empty() {
continue;
}
text_paras += 1;
if !p
.line_segs
.iter()
.any(|s| s.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
{
segless_text_paras += 1;
}
}
if segless_text_paras < 4 || segless_text_paras * 4 < text_paras {
return false;
}
let mut hits = 0usize;
let mut spacing_omitted = false;
let mut has_page_reset = false;
for pair in paragraphs.windows(2) {
let (cur, next) = (&pair[0], &pair[1]);
let (Some(cur_last), Some(next_first)) = (cur.line_segs.last(), next.line_segs.first())
else {
continue;
};
if cur_last.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
|| next_first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
{
continue;
}
if next_first.vertical_pos <= cur_last.vertical_pos {
if cur_last.vertical_pos > 5000
&& next_first.vertical_pos < 5000
&& next.controls.is_empty()
&& para_has_visible_text(next)
{
has_page_reset = true;
}
continue;
}
if spacing_omitted {
if has_page_reset {
return true;
}
continue;
}
let sa = styles
.para_styles
.get(cur.para_shape_id as usize)
.map(|s| s.spacing_after)
.unwrap_or(0.0);
let sb = styles
.para_styles
.get(next.para_shape_id as usize)
.map(|s| s.spacing_before)
.unwrap_or(0.0);
let spacing_around = sa + sb;
if spacing_around <= 2.5 {
continue;
}
let step = hwpunit_to_px(next_first.vertical_pos - cur_last.vertical_pos, dpi);
let bare = hwpunit_to_px(
cur_last.line_height.saturating_add(cur_last.line_spacing),
dpi,
);
if step <= 0.0 || bare <= 0.0 {
continue;
}
if (step - bare).abs() < 2.0 && step + 1.0 < bare + spacing_around {
hits += 1;
if hits >= 2 {
spacing_omitted = true;
if has_page_reset {
return true;
}
}
}
}
spacing_omitted && has_page_reset
}
fn debug_brief_line_text(text: &str, max_chars: usize) -> String {
let mut out = String::new();
for ch in text.chars().take(max_chars) {
match ch {
'\r' => out.push_str("\\r"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\u{FFFC}' => out.push_str("<TAC>"),
c if c.is_control() => out.push(' '),
c => out.push(c),
}
}
if text.chars().count() > max_chars {
out.push('…');
}
out
}
#[derive(Default)]
struct Issue2424TypesetProfile {
setup: std::time::Duration,
wrap_around: (std::time::Duration, u32),
text_para: (std::time::Duration, u32),
table_para: (std::time::Duration, u32),
deferred_flush: (std::time::Duration, u32),
para_tail: (std::time::Duration, u32),
endnotes: std::time::Duration,
}
impl Issue2424TypesetProfile {
fn add(bucket: &mut (std::time::Duration, u32), started: Option<std::time::Instant>) {
if let Some(started) = started {
bucket.0 += started.elapsed();
bucket.1 += 1;
}
}
fn ms(duration: std::time::Duration) -> f64 {
duration.as_secs_f64() * 1000.0
}
}
impl TypesetEngine {
pub fn new(dpi: f64) -> Self {
Self::new_with_render_normalization(
dpi,
std::sync::Arc::new(
crate::renderer::render_normalization::RenderNormalizationOverlay::default(),
),
)
}
pub(crate) fn new_with_render_normalization(
dpi: f64,
render_normalization: std::sync::Arc<
crate::renderer::render_normalization::RenderNormalizationOverlay,
>,
) -> Self {
Self {
dpi,
profile: std::cell::Cell::new(Default::default()),
section_column_spacing_hu: std::cell::Cell::new(None),
uniform_filler_ladder: std::cell::Cell::new(false),
float_carve_evidence: std::cell::RefCell::new(Vec::new()),
format_next_stored_vpos: std::cell::Cell::new(None),
render_normalization,
endnote_measure_memo: Default::default(),
}
}
pub(crate) fn with_section_column_spacing_hu(self, spacing: i32) -> Self {
self.section_column_spacing_hu.set(Some(spacing));
self
}
fn prime_section_cell_context(&self, engine: &crate::renderer::layout::LayoutEngine) {
if let Some(spacing) = self.section_column_spacing_hu.get() {
engine.set_section_column_spacing_hu(spacing);
}
}
pub(crate) fn with_render_normalization(
mut self,
overlay: std::sync::Arc<crate::renderer::render_normalization::RenderNormalizationOverlay>,
) -> Self {
self.render_normalization = overlay;
self
}
pub fn with_default_dpi() -> Self {
Self::new(DEFAULT_DPI)
}
pub(crate) fn apply_section_format_context(
&self,
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
profile: crate::model::provenance::LayoutCompatibilityProfile,
body_top_hu: i32,
) {
self.profile.set(profile);
self.uniform_filler_ladder
.set(crate::renderer::stored_line_ladder_is_uniform_filler(
paragraphs, styles,
));
*self.float_carve_evidence.borrow_mut() =
crate::renderer::float_placement::paper_or_page_float_carve_evidence(
paragraphs,
body_top_hu,
);
}
pub(crate) fn dump_formatted_paragraph_height(
&self,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
styles: &ResolvedStyleSet,
column_width_px: Option<f64>,
endnote: bool,
stored_host_plan: Option<&crate::renderer::inline_flow::InlineFlowPlan>,
next_stored_vpos: Option<i32>,
) -> DumpFormattedParagraphHeight {
let mut fmt = if endnote {
self.format_endnote_paragraph(para, composed, styles, column_width_px)
} else {
self.format_next_stored_vpos.set(next_stored_vpos);
let fmt = self.format_paragraph(para, composed, styles, column_width_px);
self.format_next_stored_vpos.set(None);
fmt
};
if let Some(plan) = stored_host_plan.filter(|plan| plan.stored_empty_host) {
fmt.use_square_host_plan(plan.clone(), self.dpi);
}
DumpFormattedParagraphHeight {
total: fmt.total_height,
spacing_before: fmt.spacing_before,
line_height_sum: fmt.line_heights.iter().sum(),
line_spacing_sum: fmt.line_spacings.iter().sum(),
spacing_after: fmt.spacing_after,
}
}
fn predict_current_column_para_y(
&self,
st: &TypesetState,
target_para_idx: usize,
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
measured_tables: &[MeasuredTable],
column_width: Option<f64>,
) -> Option<f64> {
let mut local_paras: Vec<Paragraph> = Vec::new();
let mut local_indices: Vec<(usize, usize)> = Vec::new();
for pi in st
.current_items
.iter()
.filter_map(page_item_para_index)
.chain(std::iter::once(target_para_idx))
{
if local_indices.iter().any(|(global, _)| *global == pi) {
continue;
}
if let Some(p) = paragraph_by_global_index(paragraphs, &st.endnote_paragraphs, pi) {
let local = local_paras.len();
local_paras.push(p.clone());
local_indices.push((pi, local));
}
}
let lookup_local = |pi: usize, indices: &[(usize, usize)]| {
indices
.iter()
.find_map(|(global, local)| (*global == pi).then_some(*local))
};
let first_vpos = st
.current_items
.iter()
.filter_map(page_item_para_index)
.find_map(|pi| {
paragraph_by_global_index(paragraphs, &st.endnote_paragraphs, pi)
.and_then(|p| p.line_segs.first())
.map(|seg| seg.vertical_pos)
})?;
let available = st.available_height();
let mut hc = HeightCursor::new(
self.dpi,
0.0,
available,
st.current_start_height,
Some(first_vpos),
st.skip_spacing_before_prededuct,
false,
st.current_endnote_flow && st.current_start_height < -0.5,
st.current_endnote_flow,
);
hc.endnote_between_notes_hu = st.endnote_between_notes_hu;
hc.endnote_note_first_paras =
endnote_first_local_paras(paragraphs.len(), &st.endnote_para_sources, &local_indices);
hc.stored_equation_reflow = !st.profile.session_edited()
&& (st.profile.hwp5_container() || st.profile.hwpx_stored_layout());
let mut y = st.current_start_height;
for item in &st.current_items {
let Some(pi) = page_item_para_index(item) else {
continue;
};
let Some(local) = lookup_local(pi, &local_indices) else {
continue;
};
y = hc.vpos_adjust(y, local, &local_paras, styles);
let item_para = &local_paras[local];
let item_composed =
crate::renderer::composer::compose_paragraph_in_context(item_para, styles);
let item_fmt =
self.format_paragraph(item_para, Some(&item_composed), styles, column_width);
y += match item {
PageItem::PartialParagraph {
start_line,
end_line,
..
} => item_fmt.line_advances_sum(*start_line..*end_line),
PageItem::FullParagraph { .. } => item_fmt.total_height,
PageItem::Table {
para_index,
control_index,
} => measured_tables
.iter()
.find(|mt| mt.para_index == *para_index && mt.control_index == *control_index)
.map(|mt| mt.total_height)
.unwrap_or(0.0),
PageItem::PartialTable {
para_index,
control_index,
start_row,
end_row,
..
} => measured_tables
.iter()
.find(|mt| mt.para_index == *para_index && mt.control_index == *control_index)
.map(|mt| {
let start = mt
.cumulative_heights
.get(*start_row)
.copied()
.unwrap_or(0.0);
let end = mt
.cumulative_heights
.get(*end_row)
.copied()
.unwrap_or(mt.total_height);
(end - start).max(0.0)
})
.unwrap_or(0.0),
_ => 0.0,
};
let current_vpos_rewinds_from_prev = hc
.prev_layout_para
.and_then(|prev_local| {
let prev_first = local_paras
.get(prev_local)
.and_then(|p| p.line_segs.first())
.map(|seg| seg.vertical_pos)?;
let curr_first = local_paras
.get(local)
.and_then(|p| p.line_segs.first())
.map(|seg| seg.vertical_pos)?;
Some(curr_first < prev_first)
})
.unwrap_or(false);
if matches!(
item,
PageItem::PartialParagraph { start_line, .. } if *start_line > 0
) || current_vpos_rewinds_from_prev
{
hc.prev_layout_para = None;
hc.vpos_page_base = None;
hc.vpos_lazy_base = None;
} else {
hc.prev_layout_para = Some(local);
hc.prev_reissued_equation_rows =
crate::renderer::composer::stored_row_projection::reissued_equation_rows(
item_para,
&item_composed,
);
}
hc.prev_item_was_partial_table = matches!(item, PageItem::PartialTable { .. });
}
let local = lookup_local(target_para_idx, &local_indices)?;
Some(hc.vpos_adjust(y, local, &local_paras, styles))
}
#[allow(clippy::too_many_arguments)]
pub fn typeset_section(
&self,
paragraphs: &[Paragraph],
composed: &[ComposedParagraph],
styles: &ResolvedStyleSet,
page_def: &PageDef,
column_def: &ColumnDef,
section_index: usize,
measured_tables: &[MeasuredTable],
hide_empty_line: bool,
force_break_before: &std::collections::HashSet<usize>,
) -> PaginationResult {
self.typeset_section_with_variant(
paragraphs,
composed,
styles,
page_def,
column_def,
section_index,
measured_tables,
hide_empty_line,
Default::default(),
false,
false,
None,
None,
force_break_before,
EndnoteDeferral::None,
)
}
#[allow(clippy::too_many_arguments)]
fn typeset_no_table_paragraph_tail(
&self,
st: &mut TypesetState,
page_def: &PageDef,
para: &Paragraph,
paragraphs: &[Paragraph],
composed: &[ComposedParagraph],
styles: &ResolvedStyleSet,
para_idx: usize,
has_table: bool,
) {
controls::prepare_no_table_host_wrap(st, page_def, para, para_idx, has_table);
}
fn stored_square_picture_next_page_owner(
&self,
st: &TypesetState,
para_idx: usize,
para: &Paragraph,
paragraphs: &[Paragraph],
ctrl: &Control,
styles: &ResolvedStyleSet,
) -> Option<(Vec<usize>, crate::renderer::pagination::WrapAnchorRef)> {
controls::deferred_picture::next_page_owner(
st.deferred_picture_page(),
|| st.available_height(),
self.dpi,
para_idx,
para,
paragraphs,
ctrl,
styles,
)
}
#[allow(clippy::too_many_arguments)]
fn typeset_wrap_around_paragraph(
&self,
st: &mut TypesetState,
para: &Paragraph,
paragraphs: &[Paragraph],
para_idx: usize,
has_table: bool,
page_def: &PageDef,
composed: Option<&ComposedParagraph>,
styles: &ResolvedStyleSet,
) -> bool {
controls::wrap_flow::place(
self, st, para, paragraphs, para_idx, has_table, page_def, composed, styles,
)
}
#[allow(clippy::too_many_arguments)]
pub fn typeset_section_with_variant(
&self,
paragraphs: &[Paragraph],
composed: &[ComposedParagraph],
styles: &ResolvedStyleSet,
page_def: &PageDef,
column_def: &ColumnDef,
section_index: usize,
measured_tables: &[MeasuredTable],
hide_empty_line: bool,
profile: crate::model::provenance::LayoutCompatibilityProfile,
skip_spacing_before_prededuct: bool,
hwp3_origin_page_tolerance: bool,
footnote_shape: Option<&FootnoteShape>,
endnote_shape: Option<&FootnoteShape>,
force_break_before: &std::collections::HashSet<usize>,
endnote_deferral: EndnoteDeferral<'_>,
) -> PaginationResult {
match self.typeset_section_with_variant_with_storage(
paragraphs,
composed,
styles,
page_def,
column_def,
section_index,
measured_tables,
hide_empty_line,
profile,
skip_spacing_before_prededuct,
hwp3_origin_page_tolerance,
footnote_shape,
endnote_shape,
force_break_before,
endnote_deferral,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn typeset_section_with_variant_with_storage<S: crate::storage::Storage>(
&self,
paragraphs: &[Paragraph],
composed: &[ComposedParagraph],
styles: &ResolvedStyleSet,
page_def: &PageDef,
column_def: &ColumnDef,
section_index: usize,
measured_tables: &[MeasuredTable],
hide_empty_line: bool,
profile: crate::model::provenance::LayoutCompatibilityProfile,
skip_spacing_before_prededuct: bool,
hwp3_origin_page_tolerance: bool,
footnote_shape: Option<&FootnoteShape>,
endnote_shape: Option<&FootnoteShape>,
force_break_before: &std::collections::HashSet<usize>,
endnote_deferral: EndnoteDeferral<'_>,
storage: &S,
) -> Result<PaginationResult, S::Error> {
self.run_section_with_storage(
paragraphs,
composed,
styles,
page_def,
column_def,
section_index,
measured_tables,
hide_empty_line,
profile,
skip_spacing_before_prededuct,
hwp3_origin_page_tolerance,
footnote_shape,
endnote_shape,
force_break_before,
endnote_deferral,
storage,
)
}
fn format_paragraph(
&self,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
styles: &ResolvedStyleSet,
column_width_px: Option<f64>,
) -> FormattedParagraph {
self.format_paragraph_for_flow(
para,
composed,
styles,
column_width_px,
styles.hwp3_variant,
false,
)
}
fn format_paragraph_with_known_square_band_with_storage<S: crate::storage::Storage>(
&self,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
styles: &ResolvedStyleSet,
column_width_px: Option<f64>,
known_square_band: bool,
storage: &S,
) -> Result<FormattedParagraph, S::Error> {
self.format_paragraph_for_flow_with_storage(
para,
composed,
styles,
column_width_px,
styles.hwp3_variant,
known_square_band,
storage,
)
}
fn format_paragraph_for_flow(
&self,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
styles: &ResolvedStyleSet,
column_width_px: Option<f64>,
hwp3_body_reflow: bool,
known_square_band: bool,
) -> FormattedParagraph {
match self.format_paragraph_for_flow_with_storage(
para,
composed,
styles,
column_width_px,
hwp3_body_reflow,
known_square_band,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn format_paragraph_for_flow_with_storage<S: crate::storage::Storage>(
&self,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
styles: &ResolvedStyleSet,
column_width_px: Option<f64>,
hwp3_body_reflow: bool,
known_square_band: bool,
storage: &S,
) -> Result<FormattedParagraph, S::Error> {
let context = paragraph::context::ParagraphFormatContext::new(
self.dpi,
&self.profile,
&self.uniform_filler_ladder,
&self.float_carve_evidence,
self.format_next_stored_vpos.get(),
);
paragraph::format::format_paragraph_for_flow_with_storage(
&context,
para,
composed,
styles,
column_width_px,
hwp3_body_reflow,
known_square_band,
storage,
)
}
fn typeset_paragraph(
&self,
st: &mut TypesetState,
para_idx: usize,
para: &Paragraph,
fmt: &FormattedParagraph,
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
is_last_in_section: bool,
) {
match self.typeset_paragraph_with_storage(
st,
para_idx,
para,
fmt,
paragraphs,
styles,
is_last_in_section,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn typeset_paragraph_with_storage<S: crate::storage::Storage>(
&self,
st: &mut TypesetState,
para_idx: usize,
para: &Paragraph,
fmt: &FormattedParagraph,
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
is_last_in_section: bool,
storage: &S,
) -> Result<(), S::Error> {
paragraph::flow::place_with_storage(
st,
paragraph::flow::ParagraphFlowInput {
para_idx,
para,
fmt,
paragraphs,
styles,
is_last_in_section,
},
self,
storage,
)?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn format_table(
&self,
para: &Paragraph,
para_idx: usize,
ctrl_idx: usize,
table: &crate::model::table::Table,
measured_tables: &[MeasuredTable],
styles: &ResolvedStyleSet,
composed: Option<&ComposedParagraph>,
next_para: Option<&Paragraph>,
is_column_top: bool,
) -> FormattedTable {
match self.format_table_with_storage(
para,
para_idx,
ctrl_idx,
table,
measured_tables,
styles,
composed,
next_para,
is_column_top,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn format_table_with_storage<S: crate::storage::Storage>(
&self,
para: &Paragraph,
para_idx: usize,
ctrl_idx: usize,
table: &crate::model::table::Table,
measured_tables: &[MeasuredTable],
styles: &ResolvedStyleSet,
composed: Option<&ComposedParagraph>,
next_para: Option<&Paragraph>,
is_column_top: bool,
storage: &S,
) -> Result<FormattedTable, S::Error> {
let frame_engine = crate::renderer::layout::LayoutEngine::new(self.dpi);
self.prime_section_cell_context(&frame_engine);
frame_engine.set_layout_profile(self.profile.get());
frame_engine
.set_render_normalization_overlay(std::sync::Arc::clone(&self.render_normalization));
let external_flow = frame_engine.reflow_unrestricted_table_flow(table, styles);
table::format_with_storage(
table::TableFormatInput {
para,
para_idx,
ctrl_idx,
table,
measured_tables,
styles,
composed,
next_para,
is_column_top,
external_flow,
unchanged_coanchored_frame: self.profile.get().hwp5_stored_pagination_layout()
&& !self.render_normalization.table_text_reflowed(table)
&& crate::renderer::float_placement::stored_inline_host_has_separate_float_frame(
para, table,
),
},
self.dpi,
|| self.profile.get(),
|| self.uses_tac_table_flow(table),
storage,
)
}
#[allow(clippy::too_many_arguments)]
fn flush_deferred_table_controls(
&self,
st: &mut TypesetState,
paragraphs: &[Paragraph],
composed: &[ComposedParagraph],
styles: &ResolvedStyleSet,
measured_tables: &[MeasuredTable],
flush_point: DeferredTableFlushPoint,
) {
controls::flush_deferred_tables(st, paragraphs, flush_point, |st, deferred| {
self.place_deferred_table_control(
st,
deferred,
paragraphs,
composed,
styles,
measured_tables,
);
});
}
#[allow(clippy::too_many_arguments)]
fn place_deferred_table_control(
&self,
st: &mut TypesetState,
deferred: DeferredTableControl,
paragraphs: &[Paragraph],
composed: &[ComposedParagraph],
styles: &ResolvedStyleSet,
measured_tables: &[MeasuredTable],
) {
controls::deferred_placement::place(
self,
st,
deferred,
paragraphs,
composed,
styles,
measured_tables,
);
}
#[allow(clippy::too_many_arguments)]
fn typeset_table_paragraph(
&self,
st: &mut TypesetState,
para_idx: usize,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
next_para: Option<&Paragraph>,
styles: &ResolvedStyleSet,
measured_tables: &[MeasuredTable],
_page_def: &PageDef,
paragraphs_all: &[Paragraph],
composed_all: &[ComposedParagraph],
) {
match self.typeset_table_paragraph_with_storage(
st,
para_idx,
para,
composed,
next_para,
styles,
measured_tables,
_page_def, paragraphs_all,
composed_all,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn typeset_table_paragraph_with_storage<S: crate::storage::Storage>(
&self,
st: &mut TypesetState,
para_idx: usize,
para: &Paragraph,
composed: Option<&ComposedParagraph>,
next_para: Option<&Paragraph>,
styles: &ResolvedStyleSet,
measured_tables: &[MeasuredTable],
_page_def: &PageDef,
paragraphs_all: &[Paragraph],
composed_all: &[ComposedParagraph],
storage: &S,
) -> Result<(), S::Error> {
controls::paragraph_flow::place_with_storage(
self,
st,
controls::paragraph_flow::TableParagraphInput {
para_idx,
para,
composed,
next_para,
styles,
measured_tables,
paragraphs_all,
composed_all,
},
storage,
)?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn try_typeset_empty_para_float_table(
&self,
st: &mut TypesetState,
para_idx: usize,
ctrl_idx: usize,
para: &Paragraph,
table: &crate::model::table::Table,
ft: &FormattedTable,
composed: Option<&ComposedParagraph>,
prev_para: Option<&Paragraph>,
next_para: Option<&Paragraph>,
styles: &ResolvedStyleSet,
para_start_height: f64,
lanes: &mut FloatLaneSet,
paragraphs: &[Paragraph],
) -> bool {
if self.stored_cell_page_frames_require_split(table, styles) {
return false;
}
let preceding_fragment_reflowed = st.current_items.iter().any(|item| {
let PageItem::PartialTable {
para_index,
control_index,
..
} = item
else {
return false;
};
*para_index < para_idx
&& paragraphs
.get(*para_index)
.and_then(|paragraph| paragraph.controls.get(*control_index))
.is_some_and(|control| match control {
Control::Table(previous) => {
self.render_normalization.table_text_reflowed(previous)
}
_ => false,
})
});
controls::try_place_empty_para_float_table(
st,
para_idx,
ctrl_idx,
para,
table,
ft,
composed,
prev_para,
next_para,
styles,
para_start_height,
lanes,
paragraphs,
self.render_normalization.table_text_reflowed(table),
preceding_fragment_reflowed,
self.dpi,
)
}
#[allow(clippy::too_many_arguments)]
fn typeset_tac_table(
&self,
st: &mut TypesetState,
para_idx: usize,
ctrl_idx: usize,
para: &Paragraph,
table: &crate::model::table::Table,
ft: &FormattedTable,
fmt: &FormattedParagraph,
tac_count: usize,
is_first_placed: bool,
is_last_placed: bool,
styles: &ResolvedStyleSet,
composed: Option<&ComposedParagraph>,
next_para: Option<&Paragraph>,
prev_stored_vpos: Option<i32>,
) {
let tac_table_line_idx = self.tac_table_line_index(para, table, fmt);
let prior_tac = para
.controls
.iter()
.take(ctrl_idx)
.filter(|c| matches!(c, Control::Table(t) if self.is_effective_tac_table(para, t, fmt)))
.count();
let tac_seg_idx = if tac_count > 1 {
let leading_offset = para
.controls
.iter()
.find_map(|c| match c {
Control::Table(t) if self.is_effective_tac_table(para, t, fmt) => Some(t),
_ => None,
})
.and_then(|t| self.tac_table_line_index(para, t, fmt))
.unwrap_or(0);
leading_offset + prior_tac
} else {
tac_table_line_idx.unwrap_or(0)
};
let owned_single_tac_row_height =
(st.profile.hwpx_stored_layout() && tac_count == 1 && fmt.line_heights.len() == 1)
.then(|| crate::renderer::composer::owned_rowbreak_tac_height(para, ctrl_idx))
.flatten()
.map(|height| hwpunit_to_px(height, self.dpi));
let hwpx_rowbreak_tac_missing_owned_line = st.profile.hwpx_stored_layout()
&& table.common.treat_as_char
&& table.common.flow_with_text
&& matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
&& tac_count == 1
&& para.controls.len() == 1
&& table.row_count == 3
&& table.col_count == 1
&& table.cells.len() == 3
&& !table.repeat_header
&& !para_has_visible_text(para)
&& fmt.line_heights.len() == 1
&& para.line_segs.len() == 1
&& para.line_segs.first().is_some_and(|seg| {
!is_synthetic_line_seg(seg)
&& hwpunit_to_px(seg.line_height, self.dpi) + 0.5 < ft.total_height
});
let ctrl_reset = ctrl_idx > 0
&& para.text.is_empty()
&& para.line_segs.len() == para.controls.len()
&& para
.line_segs
.get(ctrl_idx)
.map(|s| s.vertical_pos)
.unwrap_or(-1)
== 0;
let seg_reset = tac_seg_idx > 0
&& para
.line_segs
.get(tac_seg_idx)
.filter(|s| !is_synthetic_line_seg(s))
.map(|s| s.vertical_pos)
== Some(0);
let intra_para_reset = ctrl_reset || seg_reset;
if intra_para_reset && !st.current_items.is_empty() {
st.advance_column_or_new_page();
}
if is_first_placed && !st.pre_emitted_host_paras.contains(¶_idx) {
if let Some(prefix) = title_mark_prefix_advance(para, ctrl_idx, self.dpi) {
st.advance_flow_by(prefix);
}
}
let table_height = if tac_count > 1 {
let is_last_tac = prior_tac + 1 == tac_count;
let carried_anchor_ladder = st.profile.hangul2024_layout()
&& st.current_items.is_empty()
&& !para_has_visible_text(para)
&& para
.line_segs
.last()
.is_some_and(|s| s.vertical_pos == 0 && !is_synthetic_line_seg(s))
&& para
.line_segs
.get(tac_seg_idx)
.is_some_and(|s| s.vertical_pos > 0);
let charged = para
.line_segs
.get(tac_seg_idx)
.map(|seg| {
let line_h = hwpunit_to_px(seg.line_height, self.dpi);
if is_last_tac {
line_h
} else {
line_h + hwpunit_to_px(seg.line_spacing, self.dpi)
}
})
.unwrap_or(ft.total_height);
if carried_anchor_ladder {
st.record_reclaimed_host_spacing(charged);
if std::env::var("RHWP_DIAG_COMPAT24").is_ok() {
eprintln!(
"DIAG_COMPAT24 pi={para_idx} ci={ctrl_idx} carried_reclaim={charged:.1} \
total_reclaimed={:.1}",
st.hangul2024_reclaimed
);
}
0.0
} else {
charged
}
} else if let Some(owned_row_height) = owned_single_tac_row_height {
owned_row_height
} else if let Some((owner, _)) =
crate::renderer::composer::stored_owned_tac_line(para, ctrl_idx).filter(|(owner, _)| {
!st.profile.session_edited()
&& !self.render_normalization.table_text_reflowed(table)
&& fmt.line_heights.len() == para.line_segs.len()
&& *owner > 0
&& *owner + 1 < fmt.line_heights.len()
})
{
fmt.line_content_height(0..owner + 1, 0.0)
} else if tac_table_line_idx == Some(0) && fmt.line_heights.len() > 1 {
fmt.line_heights[0]
} else if intra_para_reset && tac_seg_idx < fmt.line_heights.len() {
(tac_seg_idx..fmt.line_heights.len())
.map(|li| fmt.line_advance(li))
.sum::<f64>()
} else if st.profile.hangul2024_layout()
&& tac_seg_idx > 0
&& tac_seg_idx < fmt.line_heights.len()
&& !crate::renderer::para_has_composed_object_rows(para)
&& !(st.profile.hwp5_stored_pagination_layout()
&& hwp5_tac_prefix_has_owned_object_line(para, tac_seg_idx))
{
let reclaimed = (0..tac_seg_idx).map(|li| fmt.line_advance(li)).sum::<f64>();
st.record_reclaimed_host_spacing(reclaimed);
if std::env::var("RHWP_DIAG_COMPAT24").is_ok() {
eprintln!(
"DIAG_COMPAT24 pi={para_idx} ci={ctrl_idx} anchor_reclaim={reclaimed:.1} \
tac_seg_idx={tac_seg_idx} total_reclaimed={:.1}",
st.hangul2024_reclaimed
);
}
(tac_seg_idx..fmt.line_heights.len())
.map(|li| fmt.line_advance(li))
.sum::<f64>()
} else if fmt.total_height > 0.0 {
fmt.height_for_fit
} else {
ft.total_height
};
let table_height = if para.line_segs.is_empty() && table_height + 0.5 < ft.total_height {
ft.total_height
} else {
table_height
};
let table_height = if !para.line_segs.is_empty()
&& ft.total_height > 1.0
&& table_height > ft.total_height * 2.0
&& hwpunit_to_px(table.common.height as i32, self.dpi) > ft.total_height * 2.0
{
ft.total_height
} else {
table_height
};
let band_min_px = hwpunit_to_px(table.common.height as i32, self.dpi).min(ft.total_height);
let anchor_vpos = para.line_segs.get(tac_seg_idx).map(|seg| seg.vertical_pos);
let anchor_gap_px = anchor_vpos
.zip(prev_stored_vpos)
.filter(|(anchor, prev)| anchor > prev)
.map(|(anchor, prev)| hwpunit_to_px(anchor - prev, self.dpi));
let next_gap_px = st
.next_para_first_stored_vpos
.zip(anchor_vpos)
.filter(|(next, anchor)| next > anchor)
.map(|(next, anchor)| hwpunit_to_px(next - anchor, self.dpi));
let ladder_omits_band = !st.profile.hwpx_container()
&& (!st.profile.hwp3_native_layout() || table.common.treat_as_char)
&& !para.line_segs.is_empty()
&& anchor_gap_px.is_some_and(|gap| gap < band_min_px * 0.5)
&& next_gap_px.is_some_and(|gap| gap < band_min_px * 0.5)
&& stored_ladder_omits_tac_band(
table_height,
hwpunit_to_px(table.common.height as i32, self.dpi),
ft.total_height,
);
let unstored_cell_band = self
.tac_flow_query()
.single_tac_line_has_current_cell_rows(para, table, fmt, tac_count, &ft.cells)
&& ft.total_height > table_height + 0.5;
let owns_tac_band =
ladder_omits_band || hwpx_rowbreak_tac_missing_owned_line || unstored_cell_band;
let table_height = if owns_tac_band {
if std::env::var("RHWP_5699_DBG").is_ok() {
eprintln!(
"DBG5699_TS pi={} ci={} th_charge={:.1} decl={:.1} meas={:.1} gap={:?} unowned_hwpx={}",
para_idx,
ctrl_idx,
table_height,
hwpunit_to_px(table.common.height as i32, self.dpi),
ft.total_height,
anchor_gap_px,
hwpx_rowbreak_tac_missing_owned_line,
);
}
st.mark_vpos_ladder_dirty();
st.record_ladder_band_table((para_idx, ctrl_idx));
ft.total_height
} else {
table_height
};
let column = st.inline_flow_column();
let style = styles.para_styles.get(para.para_shape_id as usize);
let left = style.map_or(0.0, |s| s.margin_left);
let right = style.map_or(0.0, |s| s.margin_right);
let owned_row = (tac_count > 1
&& st.profile.hwp5_stored_pagination_layout()
&& !st.profile.session_edited()
&& !self.render_normalization.table_text_reflowed(table)
&& ft.table_footnotes.is_empty())
.then(|| {
controls::stored_tac::owned_row::prepare(
para,
table,
ctrl_idx,
composed,
ft.effective_height,
styles,
self.dpi,
)
})
.flatten()
.or_else(|| {
((st.profile.session_edited() || table.caption.is_some())
&& ft.table_footnotes.is_empty())
.then(|| {
controls::stored_tac::owned_row::prepare_occupied(
para,
table,
ctrl_idx,
composed,
&fmt.line_heights,
ft.effective_height,
styles,
self.dpi,
)
})
.flatten()
});
let stored_host_frame = (st.profile.hwp5_stored_pagination_layout()
&& !st.profile.session_edited()
&& !self.render_normalization.table_text_reflowed(table)
&& (ft.effective_height - hwpunit_to_px(table.common.height as i32, self.dpi)).abs()
<= self.dpi / 7200.0)
.then(|| crate::renderer::composer::stored_tac_host_frame(para))
.flatten()
.filter(|frame| frame.control == ctrl_idx);
let table_height = stored_host_frame.as_ref().map_or(table_height, |frame| {
hwpunit_to_px(frame.object_advance_hu, self.dpi)
});
let before_text: f64 = if owned_row.is_some() {
0.0
} else {
(0..tac_table_line_idx.unwrap_or(0))
.map(|line| fmt.line_advance(line))
.sum()
};
let advance = hwpunit_to_px(
(table.common.width as i32)
.saturating_add(i32::from(table.outer_margin_left))
.saturating_add(i32::from(table.outer_margin_right)),
self.dpi,
);
let band_height = ft.effective_height
+ hwpunit_to_px(
i32::from(table.outer_margin_top) + i32::from(table.outer_margin_bottom),
self.dpi,
);
let exclusions: Vec<_> = st.side_wrap_exclusions.values().cloned().collect();
let natural_top = st.current_height + before_text;
let mut side_wrap_placement = super::float_placement::place_inline_box(
(column.x + left)..(column.x + column.width - right),
column.y + natural_top.max(st.inline_box_flow_bottom),
advance,
band_height,
style.map_or(crate::model::style::Alignment::Left, |s| s.alignment),
&exclusions,
self.dpi,
)
.map(|mut placement| {
placement.clearance = (placement.y - column.y - natural_top).max(0.0);
placement
});
let clearance = side_wrap_placement.map_or(0.0, |p| p.clearance);
let stored_wrap_row = controls::stored_tac::side_wrap_row(
para,
ctrl_idx,
table,
ft.effective_height,
fmt,
next_para,
next_para
.and_then(|next| styles.para_styles.get(next.para_shape_id as usize))
.map_or(0.0, |style| style.spacing_before),
st.profile,
side_wrap_placement.is_some(),
self.render_normalization.table_text_reflowed(table),
self.dpi,
);
let resolve_wrap_row = |placement: Option<super::float_placement::InlineBoxPlacement>,
column: crate::renderer::page_layout::LayoutRect,
origin: f64| {
stored_wrap_row.map(|(occupied, trailing)| {
let mut placement =
placement.unwrap_or(super::float_placement::InlineBoxPlacement {
x: column.x + left,
y: column.y + origin,
clearance: 0.0,
resolved_x: false,
stored_column_frame: None,
stored_horizontal_pen: None,
advance_end: None,
});
let leading = if origin < 1.0 {
0.0
} else {
fmt.spacing_before
};
placement.y = placement.y.max(column.y + origin + leading);
placement.clearance = placement.y - column.y - origin;
placement.advance_end = Some(placement.y - column.y + occupied + trailing);
placement
})
};
side_wrap_placement =
resolve_wrap_row(side_wrap_placement, column, natural_top).or(side_wrap_placement);
let clearance = side_wrap_placement.map_or(clearance, |placement| placement.clearance);
let table_outgrew_saved_row = st.profile.session_edited()
&& ft.effective_height > hwpunit_to_px(table.common.height as i32, self.dpi) + 0.5;
let mut table_height = if side_wrap_placement.is_some() || table_outgrew_saved_row {
table_height.max(before_text + band_height)
} else {
table_height
};
let occupied_height_for_fit = if let Some((occupied, _)) = stored_wrap_row {
occupied
} else if tac_count > 1
&& st.profile.hwp5_stored_pagination_layout()
&& !st.profile.session_edited()
&& !para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& !self.render_normalization.table_text_reflowed(table)
&& table.caption.is_none()
{
para.line_segs
.get(tac_seg_idx)
.filter(|seg| {
!is_synthetic_line_seg(seg)
&& seg.line_spacing >= 0
&& i64::from(seg.line_height)
== i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom)
&& (ft.effective_height
- hwpunit_to_px(table.common.height as i32, self.dpi))
.abs()
<= self.dpi / 7200.0
})
.map_or(table_height, |seg| hwpunit_to_px(seg.line_height, self.dpi))
} else {
table_height
};
let available = st.available_height();
let fits_after_overlay_shapes =
st.current_column_has_only_overlay_shapes() && table_height <= available + 12.0;
let tac_trailing_spacing_for_fit = if hwpx_rowbreak_tac_missing_owned_line {
(fmt.total_height - fmt.height_for_fit).max(0.0)
} else {
0.0
};
let saved_tac_table_frame_height =
stored_tac_table_frame_height(table, self.dpi, table_height);
let current_page_vpos_base = st.vpos_page_base.unwrap_or(0);
let saved_tac_table_bottom_fits = !hwpx_rowbreak_tac_missing_owned_line
&& !table_outgrew_saved_row
&& Some(current_page_vpos_base)
.and_then(|base| {
para.line_segs
.get(tac_seg_idx)
.and_then(|seg| line_seg_visible_bounds_px(seg, base, self.dpi))
})
.is_some_and(|bounds| {
saved_table_bounds_fit_at_flow_tail(
bounds,
st.current_height,
available,
saved_tac_table_frame_height,
)
});
let same_para_already_placed = st
.current_items
.iter()
.any(|it| page_item_para_index(it) == Some(para_idx));
let stored_vpos_rewind_break = st.col_count == 1
&& !st.current_items.is_empty()
&& !same_para_already_placed
&& st.current_height >= available * STORED_VPOS_REWIND_MIN_FILL
&& stored_vpos_rewinds(prev_stored_vpos, para);
if (st.current_height + clearance + occupied_height_for_fit + tac_trailing_spacing_for_fit
> available
&& (!fits_after_overlay_shapes || side_wrap_placement.is_some())
&& (!saved_tac_table_bottom_fits || side_wrap_placement.is_some())
&& !st.current_items.is_empty())
|| stored_vpos_rewind_break
{
let mut prefix_carried_separately = false;
if tac_table_line_idx
.is_some_and(|owner| crate::renderer::composer::owned_tac_prefix_rows(para, owner))
&& before_text > 0.0
&& st.current_height + fmt.line_content_height(0..tac_table_line_idx.unwrap(), 0.0)
<= available
&& !st.pre_emitted_host_paras.contains(¶_idx)
{
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: 0,
end_line: tac_table_line_idx.unwrap(),
});
st.advance_flow_by(before_text);
st.mark_pre_emitted_host(para_idx);
table_height -= before_text;
prefix_carried_separately = true;
}
st.advance_column_or_new_page();
if para.line_segs.is_empty() && !para_has_non_whitespace_text(para) {
let outer_top = hwpunit_to_px(table.outer_margin_top as i32, self.dpi);
table_height -= ft.host_spacing.before - outer_top;
}
side_wrap_placement = None;
side_wrap_placement = resolve_wrap_row(
side_wrap_placement,
st.inline_flow_column(),
st.current_height,
);
if prefix_carried_separately {
let next_column = st.inline_flow_column();
side_wrap_placement = super::float_placement::place_inline_box(
(next_column.x + left)..(next_column.x + next_column.width - right),
next_column.y + st.current_height,
advance,
band_height,
style.map_or(crate::model::style::Alignment::Left, |s| s.alignment),
&[],
self.dpi,
)
.or(Some(super::float_placement::InlineBoxPlacement {
x: next_column.x + left,
y: next_column.y + st.current_height,
clearance: 0.0,
resolved_x: true,
advance_end: None,
stored_horizontal_pen: None,
stored_column_frame: None,
}));
}
}
let leading_spacing = if st.current_height < 1.0 {
crate::renderer::stored_line_ladder::stored_column_top_spacing(
para,
fmt.spacing_before,
(st.profile.hwp5_stored_pagination_layout() || st.profile.hwpx_stored_layout())
&& !st.profile.session_edited(),
self.dpi,
)
} else {
fmt.spacing_before
};
if let Some(mut placement) = side_wrap_placement {
st.advance_flow_by(placement.clearance);
let placement_column = st.inline_flow_column();
placement.x -= placement_column.x;
placement.y -= placement_column.y;
st.record_inline_placement((para_idx, ctrl_idx), placement);
st.invalidate_vpos_after_clearance(placement.clearance);
}
if let Some(row) = owned_row.filter(|_| side_wrap_placement.is_none()) {
let stored_vertical_pen =
crate::renderer::composer::control_slot_line_index(para, ctrl_idx)
.and_then(|owner| para.line_segs.get(owner))
.filter(|line| {
line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
== 0
})
.and_then(|line| {
let previous = controls::stored_tac::owned_row::preceding_owned_row_top(
para,
para_idx,
ctrl_idx,
&st.inline_placements,
self.dpi,
);
let base = st.vpos_page_base.or(st.vpos_lazy_base).or_else(|| {
(st.current_items.is_empty()
&& st.current_height == 0.0
&& line.vertical_pos == 0)
.then_some(0)
});
let top = previous.or_else(|| {
Some(
st.vpos_col_anchor
+ hwpunit_to_px(
line.vertical_pos.checked_sub(base?)?,
self.dpi,
),
)
})?;
((top - st.current_height).abs() <= self.dpi / 7200.0).then_some(top)
});
let owns_vertical_frame = st.profile.session_edited() || stored_vertical_pen.is_some();
st.record_inline_placement(
(para_idx, ctrl_idx),
super::float_placement::InlineBoxPlacement {
x: row.horizontal_pen,
resolved_x: false,
y: st.current_height,
clearance: 0.0,
advance_end: owns_vertical_frame.then_some(st.current_height + table_height),
stored_horizontal_pen: Some(row.horizontal_pen),
stored_column_frame: None,
},
);
}
st.record_inline_flow_bottom(
st.current_height.max(st.inline_box_flow_bottom)
+ if st.pre_emitted_host_paras.contains(¶_idx) {
0.0
} else {
before_text
}
+ band_height,
);
if let Some(mut placement) = controls::physical_tac::prepare(
para,
ctrl_idx,
next_para,
next_para
.and_then(|next| styles.para_styles.get(next.para_shape_id as usize))
.map_or(0.0, |style| style.spacing_before),
fmt,
ft.effective_height,
st.profile,
self.render_normalization.inline_host_frame_expanded(table),
st.current_height,
leading_spacing,
st.available_height(),
st.stored_tac_line_frame(para, next_para, styles),
self.dpi,
) {
if let Some(inline) = st.inline_placements.get(&(para_idx, ctrl_idx)) {
placement.inline.x = inline.x;
placement.inline.clearance = inline.clearance;
}
let end = placement.end;
st.commit_stored_tac_control(para_idx, placement);
st.record_inline_flow_bottom(end);
st.protect_current_ladder_floor();
return;
}
self.place_table_with_text(
st,
para_idx,
ctrl_idx,
para,
table,
fmt,
st.current_height,
table_height,
is_first_placed,
is_last_placed,
ft.strict_following_plain_text_fit
|| hwpx_rowbreak_tac_missing_owned_line
|| unstored_cell_band
|| self.render_normalization.inline_host_frame_expanded(table),
styles,
);
if let Some(end) = side_wrap_placement.and_then(|placement| placement.advance_end) {
st.align_flow_to(end);
st.record_inline_flow_bottom(end);
}
if owns_tac_band || side_wrap_placement.is_some() {
st.protect_current_ladder_floor();
}
}
fn tac_topbottom_conflict_host_line_px(
&self,
para: &Paragraph,
table: &crate::model::table::Table,
styles: &ResolvedStyleSet,
) -> Option<f64> {
if !table.common.treat_as_char
|| !matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::TopAndBottom
)
|| para_has_non_whitespace_text(para)
{
return None;
}
let cs_id = para
.char_shape_id_at(0)
.or_else(|| para.char_shapes.first().map(|cs| cs.char_shape_id))?
as usize;
let font_size = styles.char_styles.get(cs_id)?.font_size;
if font_size <= 0.0 {
return None;
}
Some(font_size)
}
#[allow(clippy::too_many_arguments)]
fn place_table_with_text(
&self,
st: &mut TypesetState,
para_idx: usize,
ctrl_idx: usize,
para: &Paragraph,
table: &crate::model::table::Table,
fmt: &FormattedParagraph,
para_start_height: f64,
table_total_height: f64,
is_first_placed: bool,
is_last_placed: bool,
strict_following_plain_text_fit: bool,
styles: &ResolvedStyleSet,
) {
if !table.common.treat_as_char
&& matches!(
table.common.vert_rel_to,
crate::model::shape::VertRelTo::Page
)
&& matches!(table.common.vert_align, crate::model::shape::VertAlign::Top)
{
st.mark_page_absolute_top_table();
}
let vertical_offset = Self::get_table_vertical_offset(table);
let is_textless_coanchored_host = is_textless_coanchored_float_host(para);
let is_visible_para_float = is_para_topbottom_float(&table.common)
&& (para_has_non_whitespace_text(para)
|| is_textless_coanchored_host
|| crate::renderer::float_placement::whitespace_host_line_below_float(para));
let signed_vertical_offset = vertical_offset as i32;
let total_lines = fmt.line_heights.len();
let whitespace_host_line_covers_table = !para_has_non_whitespace_text(para)
&& !para.text.is_empty()
&& para
.line_segs
.iter()
.find(|ls| !is_synthetic_line_seg(ls))
.is_some_and(|ls| {
i64::from(ls.line_height)
>= i64::from(table.common.height.min(i32::MAX as u32))
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom)
- 10
});
let no_lineseg_square_host = !table.common.treat_as_char
&& matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::Square
)
&& crate::renderer::is_no_lineseg_visible_text_host(para);
let col_w_hu = crate::renderer::px_to_hwpunit(
st.layout
.column_areas
.get(st.current_column as usize)
.map_or(st.layout.body_area.width, |area| area.width),
self.dpi,
);
let no_lineseg_square_band = no_lineseg_square_host
.then(|| crate::renderer::no_lineseg_square_table_host_band(para, col_w_hu))
.flatten();
let no_lineseg_host_flows_below = no_lineseg_square_host
&& crate::renderer::no_lineseg_host_text_flows_below_square_table(para, col_w_hu)
&& fmt.square_host_plan.is_none();
let tac_table_line_idx = self.tac_table_line_index(para, table, fmt);
let has_owned_tac_prefix = para.char_offsets.len() == para.text.chars().count()
&& tac_table_line_idx.is_some_and(|line| {
crate::renderer::composer::owned_tac_prefix_rows(para, line)
&& crate::renderer::layout::control_line_seg_index(para, ctrl_idx) == Some(line)
});
let split_host_prefix = st
.paragraph_float_placements
.get(&(para_idx, ctrl_idx))
.and_then(|placement| placement.split_host_prefix());
let pre_table_end_line = if let Some(prefix) = split_host_prefix {
prefix
} else if !is_visible_para_float
&& signed_vertical_offset > 0
&& !para.text.is_empty()
&& !whitespace_host_line_covers_table
&& !st
.paragraph_float_placements
.get(&(para_idx, ctrl_idx))
.is_some_and(|placement| {
placement.stored_host_origin.is_some_and(|origin| {
placement.table_top < origin && placement.occupied_bottom <= origin
})
})
&& !(st.paragraph_float_placements.contains_key(&(para_idx, ctrl_idx))
&& !st.profile.session_edited()
&& crate::renderer::float_placement::para_offset_consumed_by_page_break(
para, table, st.base_available_height(), self.dpi,
))
&& !no_lineseg_host_flows_below
&& fmt.square_host_plan.is_none()
{
total_lines
} else if table.common.treat_as_char
&& total_lines > 1
&& (has_owned_tac_prefix
|| para.text.chars().any(|ch| {
!ch.is_whitespace()
&& ch > '\u{001F}'
&& ch != '\u{FFFC}'
&& !('\u{E000}'..='\u{F8FF}').contains(&ch)
&& (ch as u32) < 0xF0000
}))
{
tac_table_line_idx.unwrap_or(0)
} else {
0
};
let is_wrap_around_table = !table.common.treat_as_char
&& matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::Square
);
let is_first_table = is_first_placed;
if split_host_prefix.is_some() {
st.finish_deferred_host_line();
}
let defer_host_line = st.defer_host_line_item_para == Some(para_idx);
let pre_height: f64 = if pre_table_end_line > 0
&& is_first_table
&& !st.pre_emitted_host_paras.contains(¶_idx)
{
let h = fmt
.host_text_bounds(para, 0..pre_table_end_line, self.dpi)
.1;
if !defer_host_line {
st.record_host_text_fragment(para_idx, 0..pre_table_end_line, para, fmt, self.dpi);
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: 0,
end_line: pre_table_end_line,
});
}
h
} else {
0.0
};
if st.profile.hwpx_stored_layout()
&& st.col_count == 1
&& st.current_items.is_empty()
&& pre_height <= 0.5
{
if let Some(s0) = para.line_segs.first() {
let stored =
s0.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0;
let covers = s0.line_height as i64
>= table.common.height as i64
+ table.outer_margin_top as i64
+ table.outer_margin_bottom as i64;
if stored && covers {
st.record_vpos_column_anchor(st.current_height);
st.record_vpos_page_origin(Some(s0.vertical_pos));
st.record_vpos_lazy_origin(None);
st.record_vpos_origin_provenance(true);
st.record_vpos_ladder_validity(false);
}
}
}
let computed_table_body_height = hwpunit_to_px(table.common.height as i32, self.dpi);
let computed_table_outer_height = hwpunit_to_px(
i32::from(table.outer_margin_top) + i32::from(table.outer_margin_bottom),
self.dpi,
);
let computed_table_row_end = if crate::renderer::para_has_no_stored_line_segs(para)
&& is_first_table
&& is_last_placed
&& table.common.treat_as_char
&& matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::TopAndBottom
)
&& self.tac_table_line_index(para, table, fmt) == Some(0)
&& fmt.line_count() > 1
&& fmt.line_spacings[0] >= 0.0
&& (fmt.line_heights[0] - computed_table_body_height).abs() < 1.0
&& (table_total_height - computed_table_body_height).abs() < 1.0
{
let origin = st.current_height;
let end = origin + fmt.line_advance(0) + computed_table_outer_height;
st.record_inline_placement(
(para_idx, ctrl_idx),
super::float_placement::InlineBoxPlacement {
x: 0.0,
y: origin,
clearance: 0.0,
resolved_x: false,
advance_end: Some(end),
stored_horizontal_pen: None,
stored_column_frame: None,
},
);
Some(end)
} else {
None
};
let composed_table_row_origin = crate::renderer::composer::composed_tac_row(para, ctrl_idx)
.filter(|&row| {
fmt.line_count() == para.line_segs.len()
&& self.is_effective_tac_table(para, table, fmt)
&& fmt.line_heights.get(row).is_some_and(|height| {
(*height - table_total_height).abs() <= self.dpi / 7200.0
})
})
.map(|_| st.current_height + pre_height);
let mut stored_table_row_origin = None;
let stored_single_row_source = (!st.profile.session_edited()
&& is_first_placed
&& is_last_placed
&& table.common.treat_as_char
&& !para_has_non_whitespace_text(para)
&& para.controls.len() == 1
&& para.line_segs.len() == 1
&& fmt.line_heights.len() == 1
&& fmt.line_spacings.len() == 1
&& fmt.line_spacings[0] >= 0.0
&& !para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& !self.render_normalization.table_text_reflowed(table)
&& !st.inline_placements.contains_key(&(para_idx, ctrl_idx)))
.then(|| {
let line = ¶.line_segs[0];
let outer_band = i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom);
if is_synthetic_line_seg(line)
|| i64::from(line.line_height) != outer_band
|| (fmt.line_heights[0] - hwpunit_to_px(line.line_height, self.dpi)).abs()
> hwpunit_to_px(1, self.dpi)
{
return None;
}
Some((
line.vertical_pos,
st.vpos_page_base,
st.col_count == 1
&& st.current_items.is_empty()
&& st.current_height.abs() <= hwpunit_to_px(1, self.dpi),
))
})
.flatten();
if st.profile.hwp5_stored_pagination_layout()
&& !st.profile.session_edited()
&& table.common.treat_as_char
&& para.text.is_empty()
&& !para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& !self.render_normalization.table_text_reflowed(table)
&& !st.inline_placements.contains_key(&(para_idx, ctrl_idx))
{
if let Some(line_index) =
crate::renderer::layout::control_line_seg_index(para, ctrl_idx)
{
let owns_line = para.controls.iter().enumerate().all(|(index, control)| {
matches!(control, Control::Table(other) if other.common.treat_as_char
&& (index == ctrl_idx
|| crate::renderer::layout::control_line_seg_index(para, index)
!= Some(line_index)))
});
let outer_band = i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom);
let origin = st.current_height + pre_height;
let source_origin = para.line_segs.get(line_index).and_then(|line| {
let base = st.vpos_page_base.or(st.vpos_lazy_base).unwrap_or(0);
line.vertical_pos.checked_sub(base)
});
let source_pen_is_accepted = source_origin.is_some_and(|position| {
position >= 0
&& (hwpunit_to_px(position, self.dpi) - origin).abs()
<= hwpunit_to_px(2, self.dpi)
});
if owns_line
&& source_pen_is_accepted
&& para.line_segs.get(line_index).is_some_and(|line| {
!is_synthetic_line_seg(line)
&& i64::from(line.line_height) == outer_band
&& line.line_spacing >= 0
})
&& table_total_height + 0.5
>= computed_table_body_height + computed_table_outer_height
{
stored_table_row_origin = Some(origin);
}
}
}
st.append_item(PageItem::Table {
para_index: para_idx,
control_index: ctrl_idx,
});
let tac_wrap_split = table.common.treat_as_char
&& pre_table_end_line > 0
&& pre_table_end_line < total_lines;
let has_preceding_coanchored_float = is_visible_para_float
&& para.controls.iter().take(ctrl_idx).any(|control| {
matches!(control, Control::Table(previous)
if is_para_topbottom_float(&previous.common))
});
let issue2439_visible_host_stack = st.profile.hwp5_stored_pagination_layout()
&& st.col_count == 1
&& st.current_zone_y_offset.abs() < 0.5
&& is_visible_para_float
&& para_has_non_whitespace_text(para)
&& signed_vertical_offset > 0
&& has_preceding_coanchored_float
&& para
.controls
.iter()
.filter(|control| matches!(control, Control::Table(_)))
.count()
== 2
&& para.line_segs.iter().any(|seg| !is_synthetic_line_seg(seg));
let page_anchored_square = is_wrap_around_table
&& matches!(
table.common.vert_rel_to,
crate::model::shape::VertRelTo::Page | crate::model::shape::VertRelTo::Paper
);
let no_lineseg_band_host = is_wrap_around_table
&& is_first_table
&& pre_height <= 0.0
&& (fmt.square_host_plan.is_some() || no_lineseg_square_band.is_some());
if is_wrap_around_table
&& crate::renderer::para_has_no_stored_line_segs(para)
&& matches!(
table.common.vert_rel_to,
crate::model::shape::VertRelTo::Para
)
&& matches!(
table.common.horz_rel_to,
crate::model::shape::HorzRelTo::Column | crate::model::shape::HorzRelTo::Para
)
&& matches!(
table.common.horz_align,
crate::model::shape::HorzAlign::Left
)
{
let column = st.inline_flow_column();
let x0 =
column.x + hwpunit_to_px(signed_hwpunit(table.common.horizontal_offset), self.dpi);
let x1 = x0
+ hwpunit_to_px(table.common.width as i32, self.dpi)
+ hwpunit_to_px(i32::from(table.outer_margin_left), self.dpi)
+ hwpunit_to_px(i32::from(table.outer_margin_right), self.dpi);
let top = para_start_height + hwpunit_to_px(signed_vertical_offset, self.dpi);
let bottom = top
+ hwpunit_to_px(i32::from(table.outer_margin_top), self.dpi)
+ hwpunit_to_px(table.common.height as i32, self.dpi)
+ hwpunit_to_px(i32::from(table.outer_margin_bottom), self.dpi);
st.record_unstored_square_box(para_idx, x0..x1, top..bottom);
}
let empty_square_host_geometry = (is_wrap_around_table && is_first_table)
.then(|| {
let col_w_px = st
.layout
.column_areas
.get(st.current_column as usize)
.map_or(st.layout.body_area.width, |area| area.width);
crate::renderer::unstored_empty_square_table_host_geometry_px(
para,
table,
col_w_px,
styles,
styles.para_styles.get(para.para_shape_id as usize),
self.dpi,
)
})
.flatten();
if no_lineseg_band_host {
let v_off_px = crate::renderer::hwpunit_to_px(signed_vertical_offset, self.dpi);
let host_h = if fmt.square_host_plan.is_some() {
fmt.total_height
} else {
fmt.line_advances_sum(0..total_lines)
};
let host_origin = st.current_height;
let advance = if fmt.square_host_plan.is_some() {
host_h
} else {
host_h.max(v_off_px + table_total_height)
};
st.advance_flow_by(advance);
if let Some(mut plan) = fmt.square_host_plan.clone() {
plan.relative_to(0.0, -host_origin);
st.record_square_host_flow(para_idx, plan);
}
} else if let Some((table_top, below)) = empty_square_host_geometry {
st.advance_flow_by(pre_height + table_top + table_total_height + below);
} else if page_anchored_square {
st.advance_flow_by(pre_height);
st.register_page_anchored_square_table(para_idx, ctrl_idx, para, table);
} else if is_wrap_around_table
&& crate::renderer::float_placement::square_successor_starts_beside_table(
para,
st.next_para_lane_probe,
table,
)
{
if pre_height <= 0.0 {
st.register_square_band(st.current_height, st.current_height + table_total_height);
}
st.advance_flow_by(pre_height);
} else if is_wrap_around_table && pre_height > 0.0 {
let v_off_px = crate::renderer::hwpunit_to_px(vertical_offset as i32, self.dpi);
let table_bottom = v_off_px + table_total_height;
let host_origin = st.current_height;
st.register_square_band(host_origin, host_origin + pre_height.max(table_bottom));
st.advance_flow_by(pre_height.max(table_bottom));
} else if is_visible_para_float {
let resolved = st
.paragraph_float_placements
.get(&(para_idx, ctrl_idx))
.copied();
let v_off_px = hwpunit_to_px(signed_vertical_offset, self.dpi);
let outer_top_px = hwpunit_to_px(table.outer_margin_top as i32, self.dpi);
let pushed_anchor_top = crate::renderer::layout::pushed_anchor_line_table_top_px(
para, table, ctrl_idx, self.dpi,
);
let table_top = if let Some(placement) = resolved {
placement.table_top
} else if let Some(top) = pushed_anchor_top {
para_start_height + top + v_off_px
} else if signed_vertical_offset > 0 {
let anchor_offset_px = crate::renderer::layout::tac_sibling_float_anchor_offset_px(
para, table, ctrl_idx, self.dpi,
);
let stored_top = para_start_height + anchor_offset_px + outer_top_px + v_off_px;
if has_preceding_coanchored_float {
let stacked_top = if issue2439_visible_host_stack {
st.current_height + outer_top_px
} else {
st.current_height
};
stored_top.max(stacked_top)
} else {
stored_top
}
} else if st.profile.hwpx_stored_layout() {
let flow_at_para_start = (st.current_height - para_start_height).abs() < 0.5;
st.current_height
+ if flow_at_para_start {
outer_top_px
} else {
0.0
}
+ v_off_px.max(0.0)
} else {
para_start_height + outer_top_px + v_off_px
};
let resolved = resolved.or_else(|| {
(signed_vertical_offset > 0
&& para_has_non_whitespace_text(para)
&& !table.common.allow_overlap)
.then(|| {
table::block::host_placement::HostPlacementConstraint {
table,
has_preceding_coanchored_float,
dpi: self.dpi,
}
.constrain(
crate::renderer::float_placement::ParagraphFloatPlacement {
flow:
crate::renderer::float_placement::ParagraphFloatFlow::Exclusion,
anchor_y: para_start_height,
stored_host_origin: None,
stored_successor_line_origin: None,
table_left: None,
table_top,
occupied_bottom: table_top
+ table_total_height.max(0.0)
+ hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi),
},
st,
)
})
});
let table_top = resolved.map_or(table_top, |placement| placement.table_top);
let table_bottom = table_top + table_total_height.max(0.0);
let table_bottom = if let Some(mut placement) = resolved {
placement.occupied_bottom += table_top - placement.table_top;
placement.table_top = table_top;
st.record_paragraph_float_placement((para_idx, ctrl_idx), placement);
placement.occupied_bottom
} else {
table_bottom + hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi)
};
if resolved.is_some_and(|placement| placement.split_host_prefix().is_some()) {
st.align_flow_to(table_bottom);
} else if signed_vertical_offset > 0 {
if table_bottom > table_top + 0.5 {
st.add_visible_float_exclusion(VisibleFloatExclusion {
para_index: para_idx,
top: resolved.map_or(table_top, |p| p.exclusion_top(table, self.dpi)),
bottom: table_bottom,
});
}
if issue2439_visible_host_stack {
st.align_flow_to(st.current_height.max(table_bottom));
} else {
st.advance_flow_by(pre_height);
}
} else {
let resolved_frame_consumes_flow = resolved.is_some_and(|placement| {
placement.flow
== crate::renderer::float_placement::ParagraphFloatFlow::CoanchoredTable
});
let following_non_positive =
has_following_non_positive_visible_float(para, ctrl_idx);
let inter_float_gap = if !resolved_frame_consumes_flow
&& st.profile.hwpx_stored_layout()
&& following_non_positive
{
para_line_spacing_px(para, self.dpi)
} else {
0.0
};
st.align_flow_to(st.current_height.max(table_bottom + inter_float_gap));
}
} else if let Some(placement) = st
.paragraph_float_placements
.get(&(para_idx, ctrl_idx))
.filter(|placement| {
placement.flow
!= crate::renderer::float_placement::ParagraphFloatFlow::StoredSquareWrap
})
.copied()
{
if let crate::renderer::float_placement::ParagraphFloatFlow::ComputedEmptyHost {
outer_box_top,
..
} = placement.flow
{
st.add_visible_float_exclusion(VisibleFloatExclusion {
para_index: para_idx,
top: outer_box_top,
bottom: placement.occupied_bottom,
});
st.align_flow_to(placement.paragraph_end(st.current_height, fmt.spacing_after));
} else {
st.align_flow_to(placement.occupied_bottom);
}
} else if let Some(end) = computed_table_row_end {
st.align_flow_to(end);
} else if tac_wrap_split {
let prefix_continues_into_table = pre_table_end_line > 0
&& para
.line_segs
.get(pre_table_end_line)
.zip(para.line_segs.get(pre_table_end_line - 1))
.is_some_and(|(table_line, prefix_line)| {
table_line.vertical_pos > prefix_line.vertical_pos
});
let per_line_tac_height = prefix_continues_into_table
&& para
.controls
.iter()
.filter(|control| {
matches!(control, Control::Table(other)
if self.is_effective_tac_table(para, other, fmt))
})
.count()
> 1;
st.advance_flow_by(
table_total_height + if per_line_tac_height { pre_height } else { 0.0 },
);
} else if let Some(host_spacing_px) = if st.profile.hwpx_stored_layout()
&& is_last_placed
&& total_lines <= pre_table_end_line + 1
&& fmt.spacing_before + fmt.spacing_after > 0.5
&& self
.tac_topbottom_conflict_host_line_px(para, table, styles)
.is_some()
{
Some(fmt.spacing_before + fmt.spacing_after)
} else {
None
} {
st.advance_flow_by(host_spacing_px + pre_height + table_total_height);
st.mark_vpos_ladder_dirty();
if std::env::var("RHWP_DIAG_TAC").is_ok() {
eprintln!(
"DIAG_HOSTBOX pi={} add={:.1} host_sb={:.1} host_sa={:.1} stored_gap_hu={}",
para_idx,
host_spacing_px,
fmt.spacing_before,
fmt.spacing_after,
para.line_segs.first().map(|s| s.line_spacing).unwrap_or(-1),
);
}
} else {
let stored_host_line_px = para
.line_segs
.iter()
.find(|seg| !is_synthetic_line_seg(seg))
.map(|seg| crate::renderer::hwpunit_to_px(seg.line_height as i32, self.dpi));
let hangul_flowed_beside_table = is_wrap_around_table
&& table_total_height > 1.0
&& stored_host_line_px.is_some_and(|lh| lh < table_total_height * 0.25);
let next_gap_px = st
.next_para_first_stored_vpos
.zip(para.line_segs.first().map(|seg| seg.vertical_pos))
.filter(|(nv, hv)| nv > hv)
.map(|(nv, hv)| crate::renderer::hwpunit_to_px(nv - hv, self.dpi));
let hwp3_topbottom_no_reserve = (st.profile.hwp3_native_layout()
|| (st.profile.hwp3_layout() && st.profile.hwpx_container()))
&& !table.common.treat_as_char
&& matches!(
table.common.text_wrap,
crate::model::shape::TextWrap::TopAndBottom
)
&& table_total_height > 1.0
&& stored_host_line_px.is_some_and(|lh| lh < table_total_height * 0.25)
&& next_gap_px.is_some_and(|g| g < table_total_height * 0.25);
let empty_host_physical_extras_hu = ((st.profile.hwp5_stored_pagination_layout()
|| st.profile.hwpx_stored_layout())
&& st.next_para_is_empty_float_table_anchor
&& is_para_topbottom_float(&table.common)
&& !para_has_non_whitespace_text(para)
&& para
.controls
.iter()
.filter(|control| matches!(control, Control::Table(_)))
.count()
== 1)
.then(|| {
st.next_para_first_stored_vpos
.zip(
para.line_segs
.iter()
.find(|seg| !is_synthetic_line_seg(seg))
.map(|seg| seg.vertical_pos),
)
.and_then(|(next_vpos, host_vpos)| {
crate::renderer::float_placement::empty_host_physical_ladder_extras_hu(
table, host_vpos, next_vpos,
)
})
})
.flatten();
let page_band_host_line = (!table.common.treat_as_char
&& is_first_placed
&& is_last_placed
&& pre_height <= 0.0)
.then(|| {
st.page_band_host_line
.filter(|(para, ctrl, ..)| *para == para_idx && *ctrl == ctrl_idx)
.map(|(_, _, band_bottom, advance)| (band_bottom, advance))
})
.flatten()
.filter(|(band_bottom, _)| st.current_height + 0.5 < *band_bottom);
if hwp3_topbottom_no_reserve {
st.advance_flow_by(pre_height + stored_host_line_px.unwrap_or(0.0));
} else if hangul_flowed_beside_table {
let band_top = st.current_height + pre_height;
st.align_flow_to(band_top + stored_host_line_px.unwrap_or(0.0));
let frame = st.paragraph_float_placements.get(&(para_idx, ctrl_idx));
st.register_square_band(
band_top,
frame.map_or(band_top + table_total_height, |frame| frame.occupied_bottom),
);
} else if let Some((band_bottom, host_advance_hu)) = page_band_host_line {
st.align_flow_to(band_bottom);
st.advance_flow_by(hwpunit_to_px(host_advance_hu, self.dpi));
} else if let Some(extras_hu) = empty_host_physical_extras_hu {
st.advance_flow_by(
pre_height + table_total_height + hwpunit_to_px(extras_hu as i32, self.dpi),
);
} else {
st.advance_flow_by(pre_height + table_total_height);
}
}
if std::env::var("RHWP_DIAG_TAC").is_ok() {
eprintln!(
"DIAG_TAC pi={} tac={} pre_h={:.1} table_total={:.1} fmt_total={:.1} fmt_fit={:.1} stored_ls={} cur_h_after={:.1} page={} computed_end={:?} line_heights={:?} line_spacings={:?} stored_row={:?} spacing_before={} spacing_after={} reflowed={}",
para_idx,
table.common.treat_as_char,
pre_height,
table_total_height,
fmt.total_height,
fmt.height_for_fit,
!para.line_segs.is_empty(),
st.current_height,
st.pages.len(),
computed_table_row_end,
fmt.line_heights,
fmt.line_spacings,
stored_single_row_source,
fmt.spacing_before,
fmt.spacing_after,
self.render_normalization.table_text_reflowed(table),
);
}
if defer_host_line && is_last_placed {
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: 0,
end_line: pre_table_end_line.max(1),
});
st.finish_deferred_host_line();
}
let is_last_table = is_last_placed;
let tac_table_count = para
.controls
.iter()
.filter(|c| matches!(c, Control::Table(t) if self.is_effective_tac_table(para, t, fmt)))
.count();
let stored_owned_table_line = (!st.profile.session_edited()
&& fmt.line_heights.len() == para.line_segs.len())
.then(|| crate::renderer::composer::stored_owned_tac_line(para, ctrl_idx))
.flatten();
let post_table_start = if let Some((owner, _)) = stored_owned_table_line {
(owner + 1).min(total_lines)
} else if tac_wrap_split {
(pre_table_end_line + 1).min(total_lines).max(1)
} else if self.uses_tac_table_flow(table) {
pre_table_end_line.max(1)
} else if table.common.treat_as_char && total_lines > pre_table_end_line + 1 {
pre_table_end_line + 1
} else if is_last_table && !is_first_table {
0
} else {
pre_table_end_line
};
let pre_text_exists = post_table_start == 0
&& (st.pre_emitted_host_paras.contains(¶_idx)
|| st.current_items.iter().any(|item| {
matches!(item, PageItem::PartialParagraph { para_index, start_line, .. }
if *para_index == para_idx && *start_line == 0)
}));
let has_substantive_text = para_has_non_whitespace_text(para);
let whitespace_only_single_tac_host_line = !has_substantive_text
&& !para.text.is_empty()
&& table.common.treat_as_char
&& pre_table_end_line == 0
&& total_lines <= 1;
let whitespace_only_host_line_already_placed = !has_substantive_text
&& !para.text.is_empty()
&& total_lines <= 1
&& !is_first_table
&& pre_table_end_line > 0
&& post_table_start == 0;
let has_post_text = !para.text.is_empty()
&& total_lines > post_table_start
&& !whitespace_only_single_tac_host_line
&& !whitespace_only_host_line_already_placed;
let should_add_post_text = is_last_table
&& tac_table_count <= 1
&& has_post_text
&& !pre_text_exists
&& !no_lineseg_band_host;
if should_add_post_text {
let (post_content_height, post_height) =
fmt.host_text_bounds(para, post_table_start..total_lines, self.dpi);
let stored_host_origin = st
.paragraph_float_placements
.get(&(para_idx, ctrl_idx))
.and_then(|placement| placement.stored_host_origin)
.filter(|_| post_table_start == 0);
if let Some(origin) = stored_host_origin {
st.align_flow_to(origin);
} else if let Some(step) =
self.stored_tac_line_step_to_post_text(para, table, fmt, post_table_start)
{
let extra = step - table_total_height;
if extra > 0.5 {
st.advance_flow_by(extra);
} else if extra < -0.5 {
st.reclaim_flow_by(-extra);
}
}
if is_visible_para_float
&& crate::renderer::float_placement::visible_host_text_flows_below_offset_float(
para,
table,
st.next_para_first_stored_vpos,
)
{
if let Some(bottom) = st
.visible_float_exclusions
.iter()
.filter(|zone| zone.para_index == para_idx)
.map(|zone| zone.bottom)
.reduce(f64::max)
{
if bottom > st.current_height {
st.align_flow_to(bottom);
}
}
}
if is_visible_para_float && has_preceding_coanchored_float {
let first_post_line_height = fmt
.line_heights
.get(post_table_start)
.copied()
.unwrap_or(post_height);
st.apply_visible_float_exclusions(first_post_line_height, None);
if issue2439_visible_host_stack && is_last_table {
st.advance_flow_by(
hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi)
+ para_line_spacing_px(para, self.dpi),
);
}
}
let session_grown_topbottom_spill = (self.profile.get().session_edited()
|| split_host_prefix.is_some())
&& !table.common.treat_as_char
&& is_para_topbottom_float(&table.common);
let post_text_restarts_page = !self.profile.get().session_edited()
&& self
.tac_table_line_index(para, table, fmt)
.filter(|&table_line| post_table_start > table_line)
.and_then(|table_line| para.line_segs.get(table_line))
.zip(para.line_segs.get(post_table_start))
.is_some_and(|(prev, next)| stored_line_restarts_page(prev, next));
if ((self.tac_table_line_index(para, table, fmt) == Some(0)
|| session_grown_topbottom_spill)
&& st.current_height + post_content_height > st.available_height() + 0.5
|| post_text_restarts_page)
&& !st.current_items.is_empty()
{
st.advance_column_or_new_page();
}
if post_table_start == 0
&& (is_visible_para_float
|| crate::renderer::float_placement::is_absolute_topbottom_float_text_host(
para, table,
))
&& stored_host_origin.is_none()
&& st.current_height > para_start_height + 0.5
{
let spacing = crate::renderer::float_placement::float_pushed_line_spacing_before(
para_start_height,
fmt.spacing_before,
st.current_height,
);
st.consume_float_pushed_line_spacing(para_idx, spacing);
}
let post_split_line = (is_visible_para_float
&& !table.common.treat_as_char
&& !session_grown_topbottom_spill
&& st.current_height + post_height > st.available_height() + 0.5)
.then(|| {
let mut fitted = post_table_start;
for line in post_table_start..total_lines {
let content = fmt
.host_text_bounds(para, post_table_start..line + 1, self.dpi)
.0;
if st.current_height + content > st.available_height() + 0.5 {
break;
}
fitted = line + 1;
}
fitted
})
.filter(|&line| line > post_table_start && line < total_lines);
if let Some(split_line) = post_split_line {
st.record_host_text_fragment(
para_idx,
post_table_start..split_line,
para,
fmt,
self.dpi,
);
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: post_table_start,
end_line: split_line,
});
st.advance_flow_by(
fmt.host_text_bounds(para, post_table_start..split_line, self.dpi)
.1,
);
st.advance_column_or_new_page();
st.record_host_text_fragment(
para_idx,
split_line..total_lines,
para,
fmt,
self.dpi,
);
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: split_line,
end_line: total_lines,
});
st.advance_flow_by(
fmt.host_text_bounds(para, split_line..total_lines, self.dpi)
.1,
);
} else {
st.record_host_text_fragment(
para_idx,
post_table_start..total_lines,
para,
fmt,
self.dpi,
);
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: post_table_start,
end_line: total_lines,
});
st.advance_flow_by(post_height);
}
if computed_table_row_end.is_some() {
st.record_inline_flow_bottom(st.current_height);
}
} else if is_visible_para_float && is_last_table {
let next_vpos = if st.next_para_is_plain_text {
st.next_para_first_stored_vpos
} else {
None
};
if let Some(line_advance) = stored_visible_anchor_band_host_line_advance_from_vpos(
st.profile.hwp5_stored_pagination_layout() || st.profile.hwpx_stored_layout(),
para,
ctrl_idx,
next_vpos,
) {
st.advance_flow_by(hwpunit_to_px(line_advance, self.dpi));
} else if is_textless_coanchored_host
&& para.text.is_empty()
&& is_last_para_topbottom_float(para, ctrl_idx)
&& total_lines > 0
&& !para.controls.iter().any(|control| {
matches!(control, Control::Table(candidate)
if crate::renderer::empty_host_line_absorbed_by_topbottom_float(
para, &candidate.common))
})
{
st.apply_visible_float_exclusions(fmt.line_heights[0], None);
if st.current_height > para_start_height + 0.5 {
let spacing =
crate::renderer::float_placement::float_pushed_line_spacing_before(
para_start_height,
fmt.spacing_before,
st.current_height,
);
st.consume_float_pushed_line_spacing(para_idx, spacing);
}
let host_line_already_emitted = st.current_items.iter().any(|item| {
matches!(item, PageItem::PartialParagraph { para_index, start_line: 0, .. }
if *para_index == para_idx)
});
if !host_line_already_emitted {
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: 0,
end_line: 1,
});
}
st.advance_flow_by(fmt.line_advance(0));
}
}
let is_tac = self.is_effective_tac_table(para, table, fmt);
let has_following_tac_table = para.controls.iter().skip(ctrl_idx + 1).any(|control| {
matches!(control, Control::Table(next) if self.is_effective_tac_table(para, next, fmt))
});
let control_only_tail = (is_tac
&& !has_post_text
&& !has_following_tac_table
&& tac_table_count == 1
&& total_lines == para.line_segs.len()
&& self.tac_table_line_index(para, table, fmt) == Some(0))
.then(|| crate::renderer::tac_host_control_only_tail(para, 0))
.flatten();
if let Some(tail) = control_only_tail {
st.advance_flow_by(hwpunit_to_px(para.line_segs[0].line_spacing, self.dpi));
let first_tail_height = hwpunit_to_px(tail.lines[0].line_height, self.dpi);
if st.current_height + first_tail_height > st.available_height() + 0.5
&& !st.current_items.is_empty()
{
st.advance_column_or_new_page();
st.record_host_text_fragment(para_idx, 1..total_lines, para, fmt, self.dpi);
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line: 1,
end_line: total_lines,
});
}
let tail_hu: i32 = tail
.lines
.iter()
.map(|line| line.line_height + line.line_spacing)
.sum::<i32>()
- tail.lines.last().map_or(0, |line| line.line_spacing);
st.advance_flow_by(hwpunit_to_px(tail_hu, self.dpi));
}
let stored_tail = (is_last_placed
&& table.common.treat_as_char
&& table.caption.is_none()
&& !controls::stored_tac::table_has_notes(table)
&& !para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& para
.source_line_seg_vertical_pos
.as_ref()
.is_none_or(|source| {
source.len() == para.line_segs.len()
&& source
.iter()
.zip(¶.line_segs)
.all(|(&position, line)| position == line.vertical_pos)
})
&& fmt.computed_host_lines.is_none()
&& fmt.line_count() == para.line_segs.len()
&& para
.line_segs
.iter()
.all(|line| !is_synthetic_line_seg(line))
&& (para.empty_control_stream_position(0).is_some()
|| controls::order::complete_whitespace_table_stream(para)))
.then(|| crate::renderer::composer::control_slot_line_index(para, ctrl_idx))
.flatten()
.filter(|&owner| owner + 1 == para.line_segs.len())
.and_then(|owner| {
let line = ¶.line_segs[owner];
let occupied = i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom);
(line.line_spacing >= 0
&& i64::from(line.line_height) == occupied
&& (fmt.line_heights[owner] - hwpunit_to_px(line.line_height, self.dpi)).abs()
<= self.dpi / 7200.0
&& (table_total_height - fmt.line_heights[owner]).abs() <= self.dpi / 7200.0)
.then_some((owner, line))
});
let whitespace_ends_before_table = stored_tail.is_some()
&& !should_add_post_text
&& para.control_text_positions().get(ctrl_idx).copied()
== Some(para.text.chars().count());
let composed_tail_owns_spacing = crate::renderer::composer::composed_object_tail(para)
.is_some_and(|tail| tail.end == fmt.line_count());
let restore_terminal_tac_spacing = is_tac
&& (!has_post_text || whitespace_ends_before_table)
&& !has_following_tac_table
&& !composed_tail_owns_spacing;
if restore_terminal_tac_spacing {
let occupied_end = st.current_height;
st.advance_flow_by(fmt.total_height - fmt.height_for_fit);
if let Some(mut placement) = st
.inline_placements
.get(&(para_idx, ctrl_idx))
.copied()
.filter(|placement| {
placement.advance_end == Some(occupied_end)
|| (placement.stored_horizontal_pen.is_some()
&& placement
.advance_end
.is_some_and(|end| (end - occupied_end).abs() <= self.dpi / 7200.0))
})
{
placement.advance_end = Some(st.current_height);
st.record_inline_placement((para_idx, ctrl_idx), placement);
}
}
if restore_terminal_tac_spacing {
if let Some((owner, line)) = stored_tail {
let origin = st.current_height - fmt.line_advance(owner) - fmt.spacing_after;
let existing = st.inline_placements.get(&(para_idx, ctrl_idx)).copied();
let first_zero = line.vertical_pos == 0
&& origin == 0.0
&& st.vpos_col_anchor == 0.0
&& matches!(st.current_items.first(), Some(PageItem::Table { para_index, control_index })
if *para_index == para_idx && *control_index == ctrl_idx);
let base = st
.vpos_page_base
.filter(|_| st.vpos_page_base_stored)
.or_else(|| first_zero.then_some(0));
if let Some(base) = base.filter(|&base| {
let pen = st.vpos_col_anchor
+ hwpunit_to_px(line.vertical_pos.saturating_sub(base), self.dpi);
(pen - origin).abs() <= self.dpi / 7200.0
&& existing.is_none_or(|placement| {
placement.stored_column_frame.is_none()
&& placement
.advance_end
.is_none_or(|end| end == st.current_height)
&& (placement.y - origin).abs() <= self.dpi / 7200.0
})
}) {
let mut placement =
existing.unwrap_or(super::float_placement::InlineBoxPlacement {
x: 0.0,
y: origin,
clearance: 0.0,
resolved_x: false,
advance_end: None,
stored_horizontal_pen: None,
stored_column_frame: None,
});
placement.advance_end = Some(st.current_height);
placement.stored_column_frame =
Some(super::float_placement::StoredColumnFrame {
source_origin_hu: base,
column_anchor_y: st.vpos_col_anchor,
});
st.record_inline_placement((para_idx, ctrl_idx), placement);
}
}
}
let accepted_single_row_origin = stored_single_row_source.and_then(
|(source_vpos, source_base, column_started_at_zero)| {
if st.inline_placements.contains_key(&(para_idx, ctrl_idx)) {
return None;
}
let origin = st.current_height - fmt.line_advance(0) - fmt.spacing_after;
let establishes_origin = source_base.is_none()
&& st.vpos_page_base.or(st.vpos_lazy_base).is_none()
&& column_started_at_zero
&& source_vpos >= 0
&& fmt.spacing_before.is_finite()
&& fmt.spacing_before >= 0.0
&& (origin - fmt.spacing_before).abs() <= hwpunit_to_px(2, self.dpi)
&& (hwpunit_to_px(source_vpos, self.dpi) - origin).abs()
<= hwpunit_to_px(2, self.dpi);
let base = source_base.or_else(|| establishes_origin.then_some(0))?;
let source_pen = source_vpos.checked_sub(base)?;
if source_pen < 0
|| (hwpunit_to_px(source_pen, self.dpi) - origin).abs()
> hwpunit_to_px(2, self.dpi)
{
return None;
}
if establishes_origin {
st.record_paragraph_origin(super::pagination::ParagraphOrigin {
paragraph_index: para_idx,
spacing_before: fmt.spacing_before,
source_vpos_base: base,
flow_start: 0.0,
flow_end: st.current_height,
});
}
Some(origin)
},
);
let stored_table_row_origin = stored_table_row_origin
.or(accepted_single_row_origin)
.or_else(|| {
composed_table_row_origin
.filter(|_| !st.inline_placements.contains_key(&(para_idx, ctrl_idx)))
});
if let Some(origin) = stored_table_row_origin {
st.record_inline_placement(
(para_idx, ctrl_idx),
super::float_placement::InlineBoxPlacement {
x: 0.0,
y: origin,
clearance: 0.0,
resolved_x: false,
advance_end: Some(st.current_height),
stored_horizontal_pen: None,
stored_column_frame: None,
},
);
}
if std::env::var("RHWP_DIAG_TAC").is_ok() {
eprintln!(
"DIAG_TAC_END pi={} cur_h={:.1} trailing_fired={} has_post_text={} delta={:.1} accepted_origin={:?} page_base={:?} lazy_base={:?} row_advance={} inline={:?}",
para_idx,
st.current_height,
restore_terminal_tac_spacing,
has_post_text,
fmt.total_height - fmt.height_for_fit,
accepted_single_row_origin,
st.vpos_page_base,
st.vpos_lazy_base,
fmt.line_advance(0),
st.inline_placements.get(&(para_idx, ctrl_idx)),
);
}
if strict_following_plain_text_fit && is_last_placed {
st.require_strict_following_text_fit();
}
}
fn stored_tac_line_step_to_post_text(
&self,
para: &Paragraph,
table: &crate::model::table::Table,
fmt: &FormattedParagraph,
post_table_start: usize,
) -> Option<f64> {
let owner = self.tac_table_line_index(para, table, fmt)?;
if post_table_start != owner + 1 || self.profile.get().session_edited() {
return None;
}
let (table_line, post_line) = para
.line_segs
.get(owner)
.zip(para.line_segs.get(post_table_start))?;
let prefix = if owner == 0 {
0.0
} else {
let control = para.controls.iter().position(|control| {
matches!(control, Control::Table(candidate) if std::ptr::eq(candidate.as_ref(), table))
})?;
let (stored_owner, _) =
crate::renderer::composer::stored_owned_tac_line(para, control)?;
let advance = fmt.line_advances_sum(0..owner);
let stored_advance = hwpunit_to_px(
table_line
.vertical_pos
.checked_sub(para.line_segs.first()?.vertical_pos)?,
self.dpi,
);
if stored_owner != owner
|| (advance - stored_advance).abs() > hwpunit_to_px(1, self.dpi)
{
return None;
}
advance
};
if is_synthetic_line_seg(table_line)
|| is_synthetic_line_seg(post_line)
|| table_line.line_spacing == 0
{
return None;
}
let step = table_line
.vertical_pos
.checked_add(table_line.line_height)?
.checked_add(table_line.line_spacing)?;
(post_line.vertical_pos == step).then(|| {
prefix + hwpunit_to_px(table_line.line_height + table_line.line_spacing, self.dpi)
})
}
fn tac_flow_query(&self) -> controls::tac_flow::TacFlowQuery<'_> {
controls::tac_flow::TacFlowQuery::new(self.dpi, &self.profile)
}
fn tac_table_line_index(
&self,
para: &Paragraph,
table: &crate::model::table::Table,
fmt: &FormattedParagraph,
) -> Option<usize> {
self.tac_flow_query().tac_table_line_index(para, table, fmt)
}
fn is_effective_tac_table(
&self,
para: &Paragraph,
table: &crate::model::table::Table,
fmt: &FormattedParagraph,
) -> bool {
self.tac_flow_query()
.is_effective_tac_table(para, table, fmt)
}
fn uses_tac_table_flow(&self, table: &crate::model::table::Table) -> bool {
self.tac_flow_query().uses_tac_table_flow(table)
}
#[allow(clippy::too_many_arguments)]
fn pre_emit_visible_rowbreak_host_text(
&self,
st: &mut TypesetState,
para_idx: usize,
para: &Paragraph,
composed_all: &[ComposedParagraph],
styles: &ResolvedStyleSet,
) -> bool {
if !para_has_visible_text(para) {
return false;
}
self.pre_emit_deferred_host_lines(st, para_idx, para, composed_all, styles)
}
#[allow(clippy::too_many_arguments)]
fn post_emit_visible_rowbreak_host_text(
&self,
st: &mut TypesetState,
para_idx: usize,
ctrl_idx: usize,
para: &Paragraph,
table: &crate::model::table::Table,
composed_all: &[ComposedParagraph],
styles: &ResolvedStyleSet,
host_push: f64,
) -> bool {
if !crate::renderer::float_placement::partial_table_defers_visible_host(
para, table, ctrl_idx,
) || st.pre_emitted_host_paras.contains(¶_idx)
{
return false;
}
let already_emitted = st.current_items.iter().any(|item| {
matches!(item, PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. }
if *para_index == para_idx)
});
if already_emitted {
return false;
}
let Some(comp) = composed_all.get(para_idx) else {
return false;
};
let has_real_text = |line: &crate::renderer::composer::ComposedLine| {
line.runs
.iter()
.any(|run| run.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}'))
};
let Some(start_line) = comp.lines.iter().position(has_real_text) else {
return false;
};
let end_line = comp
.lines
.iter()
.rposition(has_real_text)
.map_or(comp.lines.len(), |i| i + 1);
let col_w = st
.layout
.column_areas
.get(st.current_column as usize)
.map(|a| a.width)
.unwrap_or(st.layout.body_area.width);
let host_fmt = self.format_paragraph(para, Some(comp), styles, Some(col_w));
let end_line = end_line.min(host_fmt.line_heights.len());
if start_line >= end_line {
return false;
}
let host_h = host_fmt.line_advances_sum(start_line..end_line);
let trailing_spacing = host_fmt
.line_spacings
.get(end_line - 1)
.copied()
.unwrap_or(0.0)
.max(0.0);
if st.current_height + (host_h - trailing_spacing).max(0.0) > st.available_height() {
return false;
}
st.append_item(PageItem::PartialParagraph {
para_index: para_idx,
start_line,
end_line,
});
if start_line == 0 {
st.record_float_pushed_line_spacing(para_idx, host_push.max(0.0));
}
st.advance_flow_by(host_h);
true
}
#[allow(clippy::too_many_arguments)]
fn prefill_before_deferred_table(
&self,
st: &mut TypesetState,
para_idx: usize,
para: &Paragraph,
table: &crate::model::table::Table,
paragraphs_all: &[Paragraph],
composed_all: &[ComposedParagraph],
styles: &ResolvedStyleSet,
) {
use table::deferred_float_flow::MAX_PREFILL;
if st.col_count != 1 || st.current_items.is_empty() {
return;
}
if !para_has_visible_text(para)
|| !crate::renderer::float_placement::is_para_topbottom_float(&table.common)
|| !matches!(
table.layout_page_break(),
crate::model::table::TablePageBreak::RowBreak
)
{
return;
}
let Some(host_seg) = para.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)) else {
return;
};
let host_vpos = host_seg.vertical_pos;
let body_h_hu = crate::renderer::px_to_hwpunit(st.layout.body_area.height, self.dpi);
if signed_hwpunit(table.common.vertical_offset) < 0 {
let line_ends_inside = host_vpos >= 0
&& i64::from(host_vpos) + i64::from(host_seg.line_height) <= i64::from(body_h_hu);
let next_resets = paragraphs_all
.get(para_idx + 1)
.and_then(|next| next.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)))
.is_some_and(|seg| seg.vertical_pos < host_vpos);
if !(line_ends_inside && next_resets) {
return;
}
}
let pre_emit_before_vpos_check = st.profile.hwpx_stored_layout() && host_vpos > body_h_hu;
if pre_emit_before_vpos_check
&& !self.pre_emit_visible_rowbreak_host_text(st, para_idx, para, composed_all, styles)
{
return;
}
if host_vpos < 0 || host_vpos > body_h_hu {
return; }
if !pre_emit_before_vpos_check
&& !self.pre_emit_visible_rowbreak_host_text(st, para_idx, para, composed_all, styles)
{
return;
}
let end = paragraphs_all.len().min(para_idx + 1 + MAX_PREFILL);
for next_idx in (para_idx + 1)..end {
let next = ¶graphs_all[next_idx];
if !next.controls.is_empty() {
break;
}
let Some(seg) = next.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)) else {
break;
};
if seg.vertical_pos <= host_vpos
|| seg.vertical_pos.saturating_add(seg.line_height) > body_h_hu
{
break;
}
if !self.try_append_prefilled_paragraph(
st,
next_idx,
paragraphs_all,
composed_all,
styles,
) {
break;
}
}
}
fn paragraph_has_table(&self, para: &Paragraph) -> bool {
use crate::renderer::height_measurer::is_tac_table_inline_in_para;
let seg_width = para.line_segs.first().map(|s| s.segment_width).unwrap_or(0);
para.controls.iter().any(|c| {
matches!(c, Control::Table(t) if t.attr & 0x01 == 0
|| (t.attr & 0x01 != 0 && !is_tac_table_inline_in_para(t, seg_width, para)))
})
}
fn row_has_no_text_or_controls(table: &crate::model::table::Table, row: usize) -> bool {
let mut row_cells = table
.cells
.iter()
.filter(|cell| cell.row as usize == row && cell.row_span == 1)
.peekable();
if row_cells.peek().is_none() {
return false;
}
row_cells.all(|cell| {
cell.paragraphs.iter().all(|para| {
let trimmed = para.text.replace(|c: char| c.is_control(), "");
trimmed.trim().is_empty() && para.controls.is_empty()
})
})
}
fn get_table_vertical_offset(table: &crate::model::table::Table) -> u32 {
crate::renderer::float_placement::captioned_table_flow_vertical_offset_hu(table) as u32
}
}
fn compute_body_wide_top_reserve_for_para(
para: &Paragraph,
layout: &PageLayoutInfo,
dpi: f64,
) -> f64 {
use crate::model::shape::{TextWrap, VertRelTo};
let body_w = layout.body_area.width;
let body_h = layout.available_body_height();
let body_top = layout.body_area.y;
let mut max_bottom: f64 = 0.0;
for ctrl in ¶.controls {
let common = match ctrl {
Control::Shape(s) => s.common(),
Control::Table(t) if !t.common.treat_as_char => &t.common,
Control::Picture(p) if !p.common.treat_as_char => &p.common,
_ => continue,
};
if let Some(bottom) = crate::renderer::float_placement::stored_square_top_band(
para,
ctrl,
&layout.body_area,
dpi,
) {
max_bottom = max_bottom.max(bottom - body_top);
continue;
}
if !matches!(common.text_wrap, TextWrap::TopAndBottom) || common.treat_as_char {
continue;
}
let shape_w = crate::renderer::hwpunit_to_px(common.width as i32, dpi);
if shape_w < body_w * 0.8 {
continue;
}
let shape_h = crate::renderer::hwpunit_to_px(common.height as i32, dpi);
let raw_v_offset = crate::renderer::hwpunit_to_px(common.vertical_offset as i32, dpi);
let (body_y, body_bottom) = if matches!(common.vert_rel_to, VertRelTo::Paper) {
let shape_top_abs = raw_v_offset;
let shape_bottom_abs = shape_top_abs + shape_h;
if shape_bottom_abs <= body_top {
continue;
}
(
(shape_top_abs - body_top).max(0.0),
shape_bottom_abs - body_top,
)
} else {
(raw_v_offset, raw_v_offset + shape_h)
};
if body_y > body_h / 3.0 {
continue;
}
let outer_bottom = crate::renderer::hwpunit_to_px(common.margin.bottom as i32, dpi);
let bottom = body_bottom + outer_bottom;
if bottom > max_bottom {
max_bottom = bottom;
}
}
max_bottom
}
#[cfg(test)]
mod issue_3820_saved_rowbreak_first_fragment_frame_contract {
use super::{
nearest_saved_rowbreak_frame_row_end, saved_rowbreak_first_fragment_flow_overflow_allowance,
};
#[test]
fn rejects_missing_or_unowned_saved_frames() {
assert_eq!(
saved_rowbreak_first_fragment_flow_overflow_allowance(0, true, 959.0, 970.0),
0.0,
"height=0 is not a saved first-fragment frame"
);
assert_eq!(
saved_rowbreak_first_fragment_flow_overflow_allowance(0x8000_0000, true, 959.0, 970.0,),
0.0,
"signed-wrap height is not a usable source frame"
);
assert_eq!(
saved_rowbreak_first_fragment_flow_overflow_allowance(929, false, 959.0, 970.0,),
0.0,
"an outer wrapper frame cannot authorize an inner table row cut"
);
}
#[test]
fn uses_the_absolute_fragment_bottom_not_row_space() {
assert_eq!(
saved_rowbreak_first_fragment_flow_overflow_allowance(929, true, 972.0, 970.0,),
0.0,
"the source frame may not enter the fragment-reserved bottom lane"
);
assert!(
(saved_rowbreak_first_fragment_flow_overflow_allowance(929, true, 959.0, 971.0,)
- 12.0)
.abs()
< f64::EPSILON,
"host-before flow spacing does not shrink the saved object's physical slack"
);
}
#[test]
fn frame_slack_stops_at_its_nearest_row_boundary() {
assert_eq!(
nearest_saved_rowbreak_frame_row_end(
87.0,
&[30.0, 55.0, 60.0],
&[30.0, 56.0, 60.0],
0.0
),
Some(2),
"saved-frame slack may absorb measurement drift at row 2, but not admit row 3"
);
assert_eq!(
nearest_saved_rowbreak_frame_row_end(388.0, &[36.0, 537.0], &[36.0, 472.0], 0.0),
None,
"모자란 몫(185.1)이 흡수 가능한 drift(65.0)를 넘으면 행 경계가 아니다"
);
assert_eq!(
nearest_saved_rowbreak_frame_row_end(112.6, &[30.0, 60.0], &[30.0, 60.0], 0.0),
Some(2),
"프레임이 경계를 지나면 그 행까지는 확실히 첫 조각 소유다"
);
assert_eq!(
nearest_saved_rowbreak_frame_row_end(
405.8,
&[28.4, 103.5, 163.5, 127.3],
&[28.4, 103.5, 163.5, 127.3],
0.0
),
Some(4),
"16.8px 잔여는 독립 조각이 될 수 없으므로 행을 통째로 둔다"
);
assert_eq!(
nearest_saved_rowbreak_frame_row_end(87.0, &[30.0, 55.0, 60.0], &[0.0, 0.0, 0.0], 0.0),
Some(2),
"저장 높이가 없으면 측정 최근접 스냅이 유일한 신호다"
);
}
}
#[cfg(test)]
mod issue_3780_line_advance_oob {
use super::FormattedParagraph;
fn fp(lines: usize) -> FormattedParagraph {
FormattedParagraph {
stored_ladder_is_filler: false,
exact_reflow_text_box: false,
computed_paragraph: None,
tail_line_remaining_width: None,
computed_host_lines: None,
host_composition: None,
square_host_plan: None,
total_height: 0.0,
line_heights: vec![10.0; lines],
line_spacings: vec![2.0; lines],
spacing_before: 0.0,
spacing_after: 0.0,
height_for_fit: 0.0,
tac_outer_margin_v_px: 0.0,
}
}
#[test]
fn out_of_range_line_advance_is_zero_not_panic() {
let p = fp(31);
assert_eq!(p.line_advance(31), 0.0);
assert_eq!(p.line_advance(30), 12.0, "경계 안 동작 불변");
}
#[test]
fn out_of_range_advance_sum_clamps_to_existing_lines() {
let p = fp(31);
assert_eq!(p.line_advances_sum(29..33), 24.0, "29,30 두 줄만 합산");
assert_eq!(p.line_advances_sum(0..31), 31.0 * 12.0, "전 범위 동작 불변");
assert_eq!(p.line_advances_sum(40..50), 0.0);
}
}
#[cfg(test)]
mod tests {
use crate::renderer::float_placement::native_empty_host_rowbreak_line_advance_hu;
#[test]
fn fullpage_image_single_page_policy_requires_strict_majority() {
assert!(!super::has_majority_fullpage_images(0, 0));
assert!(!super::has_majority_fullpage_images(1, 1));
assert!(!super::has_majority_fullpage_images(2, 4));
assert!(super::has_majority_fullpage_images(2, 3));
assert!(super::has_majority_fullpage_images(3, 5));
}
use super::*;
use crate::model::page::{ColumnDef, PageDef};
use crate::model::paragraph::{LineSeg, Paragraph};
use crate::model::shape::{CommonObjAttr, TextWrap, VertRelTo};
use crate::model::table::{Cell, Table, TablePageBreak};
use crate::model::Padding;
use crate::renderer::composer::ComposedParagraph;
use crate::renderer::height_measurer::HeightMeasurer;
use crate::renderer::layout::LayoutEngine;
use crate::renderer::page_layout::PageLayoutInfo;
use crate::renderer::pagination::Paginator;
use crate::renderer::style_resolver::ResolvedStyleSet;
fn a4_page_def() -> PageDef {
PageDef {
width: 59528,
height: 84188,
margin_left: 8504,
margin_right: 8504,
margin_top: 5669,
margin_bottom: 4252,
margin_header: 4252,
margin_footer: 4252,
margin_gutter: 0,
..Default::default()
}
}
#[test]
fn single_column_vpos_reset_gate_requires_exclusive_tac_picture_or_shape() {
let tac_picture = || {
let mut picture = crate::model::image::Picture::default();
picture.common.treat_as_char = true;
Control::Picture(Box::new(picture))
};
let picture_only = Paragraph {
controls: vec![tac_picture()],
..Default::default()
};
assert!(para_has_only_treat_as_char_picture_or_shape(&picture_only));
let mut table = Table::default();
table.common.treat_as_char = true;
let mixed_controls = Paragraph {
controls: vec![tac_picture(), Control::Table(Box::new(table))],
..Default::default()
};
assert!(
!para_has_only_treat_as_char_picture_or_shape(&mixed_controls),
"TAC 그림과 표가 섞인 문단은 단일 단 vpos-reset 강제 분리 대상이 아니다"
);
let picture_with_text = Paragraph {
text: "설명".to_string(),
controls: vec![tac_picture()],
..Default::default()
};
assert!(!para_has_only_treat_as_char_picture_or_shape(
&picture_with_text
));
}
#[test]
fn typeset_and_render_agree_on_inline_shape_flow_height() {
use crate::model::shape::{RectangleShape, ShapeObject};
let dpi = 96.0;
let shape = ShapeObject::Rectangle(RectangleShape {
common: CommonObjAttr {
width: 20000,
height: 2400,
treat_as_char: true,
..Default::default()
},
..Default::default()
});
let mut shape = shape;
shape.shape_attr_mut().current_height = 4066;
let expected = crate::renderer::hwpunit_to_px(shape.flow_height_hu(), dpi);
assert!(
expected > crate::renderer::hwpunit_to_px(shape.common().height as i32, dpi),
"표본 전제: 개체 표시 높이가 저장 프레임보다 크다"
);
let para = Paragraph {
text: "\u{FFFC}".to_string(),
char_count: 1,
controls: vec![Control::Shape(Box::new(shape))],
..Default::default()
};
let comp = ComposedParagraph {
lines: vec![crate::renderer::composer::ComposedLine {
runs: Vec::new(),
line_height: 4066,
baseline_distance: 0,
segment_width: 20000,
column_start: 0,
line_spacing: 0,
has_line_break: false,
char_start: 0,
}],
para_style_id: 0,
inline_controls: Vec::new(),
numbering_text: None,
tac_controls: vec![(0, 20000, 0)],
footnote_positions: Vec::new(),
tab_extended: Vec::new(),
horizontal_shaping: None,
frame_geometry: None,
};
let typeset_reserved = line_tac_picture_or_shape_height(¶, &comp, 0, dpi)
.expect("조판이 인라인 도형 줄을 인식해야 한다");
let render_reserved = crate::renderer::tac_object_flow_height_px(¶.controls[0], dpi)
.expect("렌더가 인라인 도형 높이를 산출해야 한다");
assert_eq!(typeset_reserved, render_reserved);
assert_eq!(typeset_reserved, expected);
}
fn make_paragraph_with_height(line_height: i32) -> Paragraph {
Paragraph {
line_segs: vec![LineSeg {
line_height,
..Default::default()
}],
..Default::default()
}
}
#[test]
fn composed_footnote_height_separates_body_exact_metric_from_table_queue_floor() {
let dpi = 96.0;
let empty_footnote = Footnote::default();
assert_eq!(composed_footnote_content_height(&empty_footnote, dpi), 0.0);
assert_eq!(
queued_table_footnote_content_height(&empty_footnote, dpi),
hwpunit_to_px(400, dpi),
);
let short_line = Footnote {
paragraphs: vec![Paragraph {
text: "짧음".to_string(),
char_count: 3,
line_segs: vec![LineSeg {
line_height: 200,
..Default::default()
}],
..Default::default()
}],
..Default::default()
};
assert_eq!(
composed_footnote_content_height(&short_line, dpi),
hwpunit_to_px(200, dpi),
);
assert_eq!(
queued_table_footnote_content_height(&short_line, dpi),
hwpunit_to_px(400, dpi),
);
let empty_paragraph = Footnote {
paragraphs: vec![Paragraph::default()],
..Default::default()
};
assert_eq!(
composed_footnote_content_height(&empty_paragraph, dpi),
hwpunit_to_px(400, dpi),
);
}
fn single_column_split_topology() -> Table {
let mut heading = Cell::new_empty(0, 0, 20_000, 1_000, 1);
heading.col_span = 2;
heading.paragraphs[0].text = "머리".to_string();
heading.paragraphs[0].char_count = 3;
let mut body = Cell::new_empty(0, 1, 10_000, 2_000, 2);
body.paragraphs[0].text = "긴 본문".to_string();
body.paragraphs[0].char_count = 5;
body.paragraphs[0].raw_header_extra = vec![0; 12];
body.paragraphs[0].raw_header_extra[6..10].copy_from_slice(&42_u32.to_le_bytes());
let peer = Cell::new_from_template(1, 1, 10_000, 2_000, &body);
Table {
row_count: 2,
col_count: 2,
cells: vec![heading, body, peer],
page_break: TablePageBreak::RowBreak,
..Default::default()
}
}
#[test]
fn visible_host_caption_classifier_excludes_section_headings() {
use crate::model::control::{AutoNumber, AutoNumberType, NewNumber};
let mut para = Paragraph {
text: "표 27. EU 미성년자 생존 장기기증 허용 국가 규정".to_string(),
..Default::default()
};
assert!(visible_host_is_numbered_table_caption(¶));
para.text = "Table 27. Minor living donation rules".to_string();
assert!(visible_host_is_numbered_table_caption(¶));
para.text = "1. 편성기준".to_string();
assert!(
!visible_host_is_numbered_table_caption(¶),
"#2097 section heading must not be pre-emitted as a table caption"
);
para.text = "표 작성 기준".to_string();
assert!(
!visible_host_is_numbered_table_caption(¶),
"a word beginning with 표 is not a numbered caption"
);
para.text = "표 ".to_string();
para.controls = vec![Control::AutoNumber(AutoNumber {
number_type: AutoNumberType::Table,
..Default::default()
})];
assert!(
visible_host_is_numbered_table_caption(¶),
"literal이 아닌 표 AutoNumber도 visible-host 캡션이다"
);
para.text = "번호를 다시 시작하는 표".to_string();
para.controls = vec![Control::NewNumber(NewNumber {
number_type: AutoNumberType::Table,
number: 27,
})];
assert!(visible_host_is_numbered_table_caption(¶));
para.text = "표 작성 기준".to_string();
para.controls = vec![Control::AutoNumber(AutoNumber {
number_type: AutoNumberType::Picture,
..Default::default()
})];
assert!(!visible_host_is_numbered_table_caption(¶));
para.text = "1. 편성기준".to_string();
para.controls = vec![Control::NewNumber(NewNumber {
number_type: AutoNumberType::Page,
number: 1,
})];
assert!(!visible_host_is_numbered_table_caption(¶));
}
#[test]
fn reparsed_single_column_split_topology_is_narrow() {
let split = single_column_split_topology();
assert!(
is_reparsed_single_column_cell_split_row(&split, 1),
"1열 표의 본문 셀을 1×2로 분할한 저장 구조는 식별한다"
);
assert!(
!is_reparsed_single_column_cell_split_row(&split, 0),
"전폭 행 자체는 분할 행이 아니다"
);
let mut original = split.clone();
original.col_count = 1;
original.cells.truncate(2);
original.cells[0].col_span = 1;
original.cells[1].width = 20_000;
assert!(
!is_reparsed_single_column_cell_split_row(&original, 1),
"원본 1열 giant-cell에는 strict cut을 적용하지 않는다"
);
let mut ordinary_two_column = split.clone();
ordinary_two_column.cells[2].paragraphs[0].text = "일반 우측 본문".to_string();
ordinary_two_column.cells[2].paragraphs[0].char_count = 8;
assert!(
!is_reparsed_single_column_cell_split_row(&ordinary_two_column, 1),
"병합 제목행과 일반 2열 데이터행 조합은 #2097 bottom squeeze를 보존한다"
);
let mut authored_blank = split.clone();
authored_blank.cells[2].paragraphs[0].has_para_text = true;
assert!(
!is_reparsed_single_column_cell_split_row(&authored_blank, 1),
"빈 문자열이어도 PARA_TEXT를 가진 자연 작성 셀은 분할 템플릿 빈 셀이 아니다"
);
let mut natural_blank = split.clone();
natural_blank.cells[2].paragraphs[0].raw_header_extra[6..10]
.copy_from_slice(&7_u32.to_le_bytes());
assert!(
!is_reparsed_single_column_cell_split_row(&natural_blank, 1),
"독립 instanceId를 가진 자연 작성 빈 셀은 zeroed template clone이 아니다"
);
let mut blank_left = split.clone();
blank_left.cells[1].col = 1;
blank_left.cells[2].col = 0;
assert!(
!is_reparsed_single_column_cell_split_row(&blank_left, 1),
"빈 왼쪽/본문 오른쪽의 자연 2열 행은 split_cell_into(1×2) 형상이 아니다"
);
let mut mixed_grid = split;
mixed_grid
.cells
.push(Cell::new_empty(1, 0, 10_000, 1_000, 1));
mixed_grid.cells[0].col_span = 1;
assert!(
!is_reparsed_single_column_cell_split_row(&mixed_grid, 1),
"다른 행이 원래부터 다열이면 1열→2열 분할 저장 구조가 아니다"
);
}
#[test]
fn saved_tail_fit_chain_stops_on_third_applicable_line() {
assert_eq!(
saved_tail_fit_chain_decision(0, true, false, false),
SavedTailFitChainDecision::Advance,
"첫 저장 꼬리줄은 허용한다"
);
assert_eq!(
saved_tail_fit_chain_decision(1, true, false, false),
SavedTailFitChainDecision::Advance,
"둘째 저장 꼬리줄은 허용한다"
);
assert_eq!(
saved_tail_fit_chain_decision(2, true, false, false),
SavedTailFitChainDecision::Break,
"셋째 저장 꼬리줄에서 예산 초과 연쇄를 끊는다"
);
}
#[test]
fn saved_tail_fit_chain_keeps_authoritative_boundary_exceptions() {
assert_eq!(
saved_tail_fit_chain_decision(2, true, true, false),
SavedTailFitChainDecision::NoChange,
"HWP 권위 경계는 저장 꼬리줄 상한으로 중단하지 않는다"
);
assert_eq!(
saved_tail_fit_chain_decision(2, true, false, true),
SavedTailFitChainDecision::NoChange,
"native HWP5 실제 각주 경계 예외는 저장 꼬리줄 상한으로 중단하지 않는다"
);
assert_eq!(
saved_tail_fit_chain_decision(2, false, false, false),
SavedTailFitChainDecision::NoChange,
"저장 꼬리줄 판정이 아니면 연쇄 상태를 바꾸지 않는다"
);
}
#[test]
fn saved_line_clears_footnote_area_requires_every_boundary() {
let allows = |footnote_height, is_single_column, overflow, bounds, current_height| {
saved_line_clears_footnote_area(
footnote_height,
is_single_column,
overflow,
bounds,
1_000.0,
current_height,
current_height,
)
};
let allows_in_fragment = |bounds, fragment_top, line_top| {
saved_line_clears_footnote_area(
300.0,
true,
0.0,
bounds,
1_000.0,
fragment_top,
line_top,
)
};
assert!(
allows_in_fragment(Some((230.0, 245.0)), 200.0, 250.0),
"조각 둘째 줄 이후의 저장 줄은 그 줄의 흐름 위치까지 받는다"
);
assert!(
!allows_in_fragment(Some((250.1, 265.0)), 200.0, 250.0),
"저장 줄이 그 줄의 흐름 위치보다 낮으면 받지 않는다"
);
assert!(
!allows_in_fragment(Some((183.9, 198.0)), 200.0, 250.0),
"조각 시작보다 허용오차 넘게 위인 저장 줄은 받지 않는다"
);
assert!(
allows(300.0, true, 0.0, Some((200.0, 700.0)), 216.0),
"각주 위 저장 좌표, 넘침 없음, 16px 흐름 허용오차의 경계값은 허용한다"
);
assert!(
!allows(0.0, true, 0.0, Some((200.0, 700.0)), 216.0),
"각주가 없으면 예외를 적용하지 않는다"
);
assert!(
!allows(300.0, false, 0.0, Some((200.0, 700.0)), 216.0),
"다단에는 적용하지 않는다"
);
assert!(
!allows(300.0, true, 0.1, Some((200.0, 700.0)), 216.0),
"각주 위 저장 좌표라도 본문 끝을 넘는 줄은 허용하지 않는다"
);
assert!(
!allows(300.0, true, 0.0, Some((200.0, 700.1)), 216.0),
"저장 줄 하단이 각주 영역에 닿으면 허용하지 않는다"
);
assert!(
!allows(300.0, true, 0.0, Some((-0.1, 700.0)), 0.0),
"쪽 밖 음수 저장 좌표는 허용하지 않는다"
);
assert!(
!allows(300.0, true, 0.0, Some((1_000.1, 700.0)), 0.0),
"본문 높이를 넘는 저장 좌표는 허용하지 않는다"
);
assert!(
!allows(300.0, true, 0.0, Some((200.0, 700.0)), 216.1),
"흐름 커서가 저장 좌표보다 낮으면 허용하지 않는다"
);
}
#[test]
fn stored_host_anchor_requires_next_ladder_room() {
let table = Table {
common: CommonObjAttr {
height: 18_000,
..Default::default()
},
outer_margin_top: 500,
outer_margin_bottom: 300,
..Default::default()
};
let host = Paragraph {
line_segs: vec![LineSeg {
vertical_pos: 1_000,
line_height: 1_100,
..Default::default()
}],
..Default::default()
};
let short_ladder = Paragraph {
line_segs: vec![LineSeg {
vertical_pos: 2_500,
..Default::default()
}],
..Default::default()
};
assert!(
!stored_ladder_leaves_object_room(&host, Some(&short_ladder), &table),
"짧은 다음-vpos 간격은 raw anchor의 저장 증거가 아니다"
);
let full_ladder = Paragraph {
line_segs: vec![LineSeg {
vertical_pos: 19_800,
..Default::default()
}],
..Default::default()
};
assert!(
stored_ladder_leaves_object_room(&host, Some(&full_ladder), &table),
"다음 저장 vpos가 표 높이와 바깥 여백을 모두 비우면 사다리 증거다"
);
let covered_host = Paragraph {
line_segs: vec![LineSeg {
vertical_pos: 1_000,
line_height: 18_800,
..Default::default()
}],
..Default::default()
};
assert!(
!stored_ladder_leaves_object_room(&covered_host, None, &table),
"host 줄 높이는 #3738 표적을 되살릴 수 있어 다음-vpos 사다리 없이 raw anchor의 증거가 아니다"
);
}
#[test]
fn stored_vpos_rewind_ignores_synthetic_line_segments() {
let previous = Paragraph {
line_segs: vec![
LineSeg {
vertical_pos: 41_645,
..Default::default()
},
LineSeg {
vertical_pos: 0,
tag: LineSeg::TAG_IMPLEMENTATION_PROPERTY,
..Default::default()
},
],
..Default::default()
};
let current = Paragraph {
line_segs: vec![
LineSeg {
vertical_pos: 0,
tag: LineSeg::TAG_IMPLEMENTATION_PROPERTY,
..Default::default()
},
LineSeg {
vertical_pos: 1_000,
..Default::default()
},
],
..Default::default()
};
let paragraphs = vec![previous, current.clone()];
let previous_vpos = preceding_stored_vpos(¶graphs, 1);
assert_eq!(previous_vpos, Some(41_645));
assert!(stored_vpos_rewinds(previous_vpos, ¤t));
}
fn hwpx_tail_page_break_candidate(break_type: ColumnBreakType) -> (Paragraph, Paragraph) {
let paragraph = Paragraph {
text: "앞 줄\n마지막 줄".to_string(),
line_segs: vec![
LineSeg {
vertical_pos: 6_000,
line_height: 1_000,
..Default::default()
},
LineSeg {
vertical_pos: 0,
line_height: 1_000,
..Default::default()
},
],
..Default::default()
};
let next = Paragraph {
column_type: break_type,
..Default::default()
};
(paragraph, next)
}
#[test]
fn hwpx_explicit_page_break_tail_splits_only_last_stored_line() {
for break_type in [ColumnBreakType::Page, ColumnBreakType::Section] {
let (paragraph, next) = hwpx_tail_page_break_candidate(break_type);
assert_eq!(
hwpx_explicit_page_break_tail_line(¶graph, Some(&next), 2, 100.0, DEFAULT_DPI,),
Some(1),
"{break_type:?} 명시 나눔 앞의 vpos=0 tail만 분리해야 한다"
);
}
}
#[test]
fn hwpx_explicit_page_break_tail_requires_all_stored_layout_evidence() {
let rejects = |paragraph: Paragraph, next: Paragraph, line_count| {
assert_eq!(
hwpx_explicit_page_break_tail_line(
¶graph,
Some(&next),
line_count,
100.0,
DEFAULT_DPI,
),
None,
"불완전한 저장 증거는 일반 문단 쪽 경계로 승격하면 안 된다"
);
};
let (paragraph, _) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
rejects(paragraph, Paragraph::default(), 2);
let (paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Column);
rejects(paragraph, next, 2);
let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
paragraph.line_segs[1].vertical_pos = 1;
rejects(paragraph, next, 2);
let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
paragraph.line_segs.push(LineSeg::default());
rejects(paragraph, next, 2);
let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
paragraph.line_segs[0].vertical_pos = 3_000;
rejects(paragraph, next, 2);
let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
paragraph.line_segs[0].vertical_pos = 7_000;
rejects(paragraph, next, 2);
}
#[test]
fn issue2439_native_empty_host_rowbreak_evidence_is_narrow() {
let table = Table {
page_break: TablePageBreak::RowBreak,
common: CommonObjAttr {
treat_as_char: false,
text_wrap: TextWrap::TopAndBottom,
vert_rel_to: VertRelTo::Para,
vertical_offset: 350,
..Default::default()
},
..Default::default()
};
let anchor = Paragraph {
line_segs: vec![LineSeg {
line_height: 1200,
line_spacing: 240,
..Default::default()
}],
controls: vec![Control::Table(Box::new(table.clone()))],
..Default::default()
};
let signature = Paragraph {
text: "signature".to_string(),
line_segs: vec![LineSeg {
line_height: 1000,
vertical_pos: 1440,
..Default::default()
}],
..Default::default()
};
let line_advance =
native_empty_host_rowbreak_line_advance_hu(true, &anchor, &table, Some(&signature))
.expect("native evidence line advance");
assert_eq!(line_advance, 1440);
let tail = hwpunit_to_px(line_advance + 350, DEFAULT_DPI);
assert!(
(tail - hwpunit_to_px(1790, DEFAULT_DPI)).abs() < 0.01,
"tail must be stored line advance + positive vertical_offset"
);
assert!(native_empty_host_rowbreak_line_advance_hu(
false,
&anchor,
&table,
Some(&signature),
)
.is_none());
assert!(native_empty_host_rowbreak_line_advance_hu(
true,
&anchor,
&table,
Some(&Paragraph::new_empty()),
)
.is_none());
let mut two_tables = anchor.clone();
two_tables
.controls
.push(Control::Table(Box::new(table.clone())));
assert!(native_empty_host_rowbreak_line_advance_hu(
true,
&two_tables,
&table,
Some(&signature),
)
.is_none());
let mut physical_ladder_signature = signature.clone();
physical_ladder_signature.line_segs[0].vertical_pos = 11202;
assert!(native_empty_host_rowbreak_line_advance_hu(
true,
&anchor,
&table,
Some(&physical_ladder_signature),
)
.is_none());
}
fn issue2814_half_page_picture(height_hu: u32) -> Control {
use crate::model::shape::{TextWrap, VertRelTo};
let mut pic = crate::model::image::Picture::default();
pic.common.treat_as_char = false;
pic.common.text_wrap = TextWrap::TopAndBottom;
pic.common.vert_rel_to = VertRelTo::Para;
pic.common.width = 40000;
pic.common.height = height_hu;
Control::Picture(Box::new(pic))
}
fn issue2814_typeset_pages(host: Paragraph) -> Vec<usize> {
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let paras = vec![host];
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let (_, measured) = paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
result
.pages
.iter()
.map(|page| {
page.column_contents
.iter()
.flat_map(|col| col.items.iter())
.filter(|item| matches!(item, PageItem::Shape { .. }))
.count()
})
.collect()
}
#[test]
fn issue2814_multi_coanchored_half_page_pictures_distribute_across_pages() {
let mut host = make_paragraph_with_height(900);
host.controls = (0..6).map(|_| issue2814_half_page_picture(30000)).collect();
let shapes_per_page = issue2814_typeset_pages(host);
assert_eq!(
shapes_per_page,
vec![2, 2, 2],
"절반쪽 그림 6장은 쪽당 2장씩 3쪽으로 분배되어야 한다",
);
}
#[test]
fn issue2814_two_picture_stack_keeps_current_page() {
let mut host = make_paragraph_with_height(900);
host.controls = (0..2).map(|_| issue2814_half_page_picture(35000)).collect();
let shapes_per_page = issue2814_typeset_pages(host);
assert_eq!(
shapes_per_page,
vec![2],
"2장 스택은 쪽 이월 없이 현재 쪽을 유지해야 한다",
);
}
#[test]
fn issue2439_strict_following_plain_text_fit_is_consumed_once() {
let plain = Paragraph {
text: "signature".to_string(),
..Default::default()
};
let mut pending = true;
assert!(take_strict_plain_text_fit_after_empty_host_float_once(
&mut pending,
&plain
));
assert!(!pending);
assert!(!take_strict_plain_text_fit_after_empty_host_float_once(
&mut pending,
&plain
));
let mut pending = true;
assert!(!take_strict_plain_text_fit_after_empty_host_float_once(
&mut pending,
&Paragraph::new_empty(),
));
assert!(
pending,
"an ineligible paragraph must not consume the one-shot"
);
assert!(take_strict_plain_text_fit_after_empty_host_float_once(
&mut pending,
&plain,
));
assert_eq!(paragraph_page_end_fit_height(21.3, 13.3, false), 13.3);
assert_eq!(paragraph_page_end_fit_height(21.3, 13.3, true), 21.3);
}
fn issue2439_cut_paragraph(line_count: usize, line_height: i32) -> Paragraph {
Paragraph {
text: "가".repeat(line_count),
char_count: line_count as u32,
line_segs: (0..line_count)
.map(|line| LineSeg {
vertical_pos: line as i32 * line_height,
line_height,
text_height: line_height,
line_spacing: 0,
..Default::default()
})
.collect(),
..Default::default()
}
}
#[test]
fn issue2439_row_orphan_guard_uses_padded_visible_fragment_height() {
let cells = (0..33u16)
.map(|col| Cell {
row: 0,
col,
row_span: 1,
col_span: 1,
width: if col == 32 { 5421 } else { 1940 },
height: 2693,
paragraphs: vec![if col == 32 {
issue2439_cut_paragraph(3, 900)
} else {
issue2439_cut_paragraph(1, 1000)
}],
..Default::default()
})
.collect();
let table = Table {
row_count: 1,
col_count: 33,
padding: Padding {
left: 510,
right: 510,
top: 141,
bottom: 141,
},
page_break: TablePageBreak::RowBreak,
cells,
..Default::default()
};
let engine = LayoutEngine::new(DEFAULT_DPI);
let styles = ResolvedStyleSet::default();
let cut = engine.advance_row_cut(&table, 0, &[], 35.6, &styles);
let mut expected_cut = vec![1usize; 33];
expected_cut[32] = 2;
assert_eq!(
cut.end_cut, expected_cut,
"remarks must retain its third line"
);
assert!(!cut.fully_consumed);
assert!(
cut.consumed_height < MIN_TOP_KEEP_PX,
"fixture must exercise the former content-only orphan rejection: {}",
cut.consumed_height,
);
let visible_height = engine.row_cut_content_height(&table, 0, &[], &cut.end_cut, &styles);
assert!(
visible_height > cut.consumed_height,
"visible fragment must include vertical padding: content={}, visible={visible_height}",
cut.consumed_height,
);
assert!(
!row_split_meets_min_top_keep(cut.consumed_height, visible_height, false),
"ordinary RowBreak tables must keep the content-only orphan guard",
);
assert!(
row_split_meets_min_top_keep(cut.consumed_height, visible_height, true),
"the strict #2439 padded cut must remain on the current page: {visible_height}",
);
}
#[test]
fn issue2439_partial_rowbreak_repeats_outer_margins_without_repeating_vertical_offset() {
let table = Table {
page_break: TablePageBreak::RowBreak,
outer_margin_top: 283,
outer_margin_bottom: 283,
common: CommonObjAttr {
treat_as_char: false,
text_wrap: TextWrap::TopAndBottom,
vert_rel_to: VertRelTo::Para,
vertical_offset: 399,
..Default::default()
},
..Default::default()
};
let outer = hwpunit_to_px(283, DEFAULT_DPI);
let first_host_before = outer + 2.0;
let first = partial_rowbreak_fragment_spacing_px(
&table,
first_host_before,
false,
true,
false,
DEFAULT_DPI,
);
let continuation = partial_rowbreak_fragment_spacing_px(
&table,
first_host_before,
true,
true,
false,
DEFAULT_DPI,
);
assert!((first.0 - first_host_before).abs() < 0.01);
assert!((first.1 - outer).abs() < 0.01);
assert!((continuation.0 - outer).abs() < 0.01);
assert!((continuation.1 - outer).abs() < 0.01);
assert_eq!(table.common.vertical_offset, 399);
let ungated = partial_rowbreak_fragment_spacing_px(
&table,
first_host_before,
true,
false,
false,
DEFAULT_DPI,
);
assert_eq!(ungated, (0.0, 0.0));
}
fn para_at_vpos(vpos: i32) -> Paragraph {
Paragraph {
line_segs: vec![LineSeg {
vertical_pos: vpos,
line_height: 1300,
text_height: 1300,
..Default::default()
}],
..Default::default()
}
}
#[test]
fn issue2424_table_continuation_cursor_preserves_break_state() {
let mut cursor = TableContinuationCursor::default();
assert_eq!(cursor.row, 0);
assert!(!cursor.is_continuation);
assert_eq!(cursor.fragments_emitted, 0);
cursor.advance(3, None, vec![4, 7], true);
assert_eq!(
cursor.row, 2,
"ordinary intra-row split resumes at end_row-1"
);
assert_eq!(cursor.start_cut, vec![4, 7]);
assert!(!cursor.start_cut_is_block);
assert!(cursor.is_continuation);
assert_eq!(cursor.fragments_emitted, 1);
cursor.advance(3, Some(1), vec![8], true);
assert_eq!(cursor.row, 1, "rowspan block split resumes at block start");
assert_eq!(cursor.start_cut, vec![8]);
assert!(cursor.start_cut_is_block);
assert_eq!(cursor.fragments_emitted, 2);
cursor.advance(3, None, vec![99], false);
assert_eq!(cursor.row, 3, "whole-row consumption resumes at end_row");
assert!(cursor.start_cut.is_empty());
assert!(!cursor.start_cut_is_block);
assert_eq!(cursor.fragments_emitted, 3);
cursor.skip_consumed_row();
assert_eq!(cursor.row, 4);
assert_eq!(cursor.fragments_emitted, 3, "skipping emits no fragment");
cursor.finish(9, true);
assert_eq!(cursor.row, 9);
assert!(cursor.start_cut.is_empty());
assert_eq!(cursor.fragments_emitted, 4);
}
#[test]
fn issue2424_block_table_context_owns_step_lifecycle() {
let prepared = BlockTableContinuationPreparedState {
computed_host_tail: None,
first_anchor_offset_consumed: false,
opening_rowspan_block_cuts_after_first_row: false,
host_placement: None,
empty_opening_row_frame: None,
source_text_first_frame_height: None,
source_terminal_suffix_start: None,
source_single_cell_row_frames: None,
host_frame: (0, 0, 0.0_f64.to_bits()),
row_count: 3,
cell_spacing: 0.0,
can_intra_split: true,
base_available: 100.0,
table_available: 100.0,
layout_engine: crate::renderer::layout::LayoutEngine::new(DEFAULT_DPI),
rowspan_touched: vec![false; 3],
cut_row_heights: vec![10.0; 3],
whole_row_fit_heights: vec![10.0; 3],
stored_rewinding_rowbreak_uses_painted_row_footprint: false,
first_fragment_painted_row_footer_guard: 0.0,
caption_is_top: false,
caption_overhead: 0.0,
total_rows_height: 30.0,
total_footnote_height: 0.0,
queue_table_footnotes: false,
table_footnotes: Vec::new(),
host_spacing_total: 0.0,
host_spacing_before: 0.0,
host_spacing_after_only: 0.0,
terminal_outer_bottom_flow: 0.0,
terminal_host_spacing: 0.0,
strict_following_plain_text_fit: false,
budget_para_start_height: 0.0,
first_fragment_actual_footnote_boundary: None,
source_next_positive_rewind: false,
first_fragment_saved_offset: None,
source_cellbreak_row_end: None,
next_para_stored_top: None,
relax_terminal_table_footnote_fit: false,
host_line_trails_table: false,
};
let flow_layout =
PageLayoutInfo::from_page_def(&a4_page_def(), &ColumnDef::default(), DEFAULT_DPI);
let flow_state = TypesetState::new(flow_layout, 1, 0, 0.0, 0.0, Default::default());
let mut context = BlockTableContinuationContext::new(0, prepared, flow_state);
assert_eq!(context.fragment_budget, 1, "zero budget clamps to one");
assert_eq!(context.steps_completed, 0);
assert!(!context.is_complete());
context.step(|_, _, cursor| {
cursor.advance(2, None, vec![4], true);
TableContinuationIteration::Emitted
});
assert_eq!(context.steps_completed, 1);
assert_eq!(context.cursor.fragments_emitted, 1);
assert!(!context.is_complete());
context.step(|_, _, cursor| {
cursor.finish(3, true);
TableContinuationIteration::Complete
});
assert!(context.is_complete());
assert_eq!(context.steps_completed, 2);
assert_eq!(context.cursor.fragments_emitted, 2);
let flow_state = context.into_flow_state();
assert_eq!(flow_state.section_index, 0);
}
#[test]
fn test_saved_flow_marks_page_last() {
let doc_end = vec![para_at_vpos(0), para_at_vpos(72626)];
assert!(saved_flow_marks_page_last(&doc_end, 1));
let reset = vec![para_at_vpos(72626), para_at_vpos(700)];
assert!(saved_flow_marks_page_last(&reset, 0));
let cumulative = vec![para_at_vpos(72626), para_at_vpos(74902)];
assert!(!saved_flow_marks_page_last(&cumulative, 0));
let with_empty = vec![
para_at_vpos(72626),
Paragraph::default(),
para_at_vpos(74902),
];
assert!(!saved_flow_marks_page_last(&with_empty, 0));
let mut page_break_next = para_at_vpos(140204);
page_break_next.column_type = ColumnBreakType::Page;
let cumulative_with_break = vec![para_at_vpos(137484), page_break_next];
assert!(saved_flow_marks_page_last(&cumulative_with_break, 0));
}
fn page_with_items(items: Vec<PageItem>) -> PageContent {
PageContent {
page_index: 0,
page_number: 0,
page_number_restarted: false,
section_index: 0,
layout: PageLayoutInfo::from_page_def(
&a4_page_def(),
&ColumnDef::default(),
DEFAULT_DPI,
),
column_contents: vec![ColumnContent {
paragraph_origins: Default::default(),
computed_paragraphs: Default::default(),
column_index: 0,
start_height: 0.0,
endnote_flow: false,
items,
zone_layout: None,
zone_y_offset: 0.0,
wrap_around_paras: Vec::new(),
used_height: 0.0,
wrap_anchors: std::collections::HashMap::new(),
overlay_continuations: Vec::new(),
overlay_cuts: Vec::new(),
inline_placements: Default::default(),
inline_flow_plans: Default::default(),
stored_paragraph_flow_ends: Default::default(),
host_compositions: Default::default(),
stored_column_top_spacings: Default::default(),
paragraph_float_placements: Default::default(),
float_pushed_line_spacings: Default::default(),
page_band_flow_starts: Default::default(),
}],
active_header: None,
active_footer: None,
page_number_pos: None,
page_hide: None,
footnotes: Vec::new(),
active_master_page: None,
extra_master_pages: Vec::new(),
ladder_band_tables: Vec::new(),
}
}
fn assert_pagination_match(old: &PaginationResult, new: &PaginationResult, label: &str) {
assert_eq!(
old.pages.len(),
new.pages.len(),
"{}: 페이지 수 불일치 (old={}, new={})",
label,
old.pages.len(),
new.pages.len(),
);
for (pi, (old_page, new_page)) in old.pages.iter().zip(new.pages.iter()).enumerate() {
assert_eq!(
old_page.column_contents.len(),
new_page.column_contents.len(),
"{}: p{} 단 수 불일치",
label,
pi,
);
for (ci, (old_col, new_col)) in old_page
.column_contents
.iter()
.zip(new_page.column_contents.iter())
.enumerate()
{
assert_eq!(
old_col.items.len(),
new_col.items.len(),
"{}: p{} col{} 항목 수 불일치 (old={}, new={})",
label,
pi,
ci,
old_col.items.len(),
new_col.items.len(),
);
}
}
}
#[test]
fn test_typeset_engine_creation() {
let engine = TypesetEngine::new(96.0);
assert_eq!(engine.dpi, 96.0);
}
#[test]
fn test_typeset_empty_paragraphs() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
&[],
&composed,
&styles,
&a4_page_def(),
&ColumnDef::default(),
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 1, "빈 문서도 최소 1페이지");
}
#[test]
fn table_continuation_does_not_reapply_page_hide() {
let hide = crate::model::control::PageHide {
hide_master_page: true,
hide_page_num: true,
..Default::default()
};
let mut pages = vec![
page_with_items(vec![PageItem::PartialTable {
para_index: 7,
control_index: 0,
start_row: 0,
end_row: 2,
is_continuation: false,
start_cut: Vec::new(),
end_cut: Vec::new(),
is_block_split: false,
start_cut_is_block: false,
row_cursor_is_nested: false,
end_row_height_override: None,
start_row_height_override: None,
straddle_row_relief: Vec::new(),
straddle_page_bands: Vec::new(),
fragment_row_heights: None,
fragment_block_frames: Vec::new(),
end_row_owns_stored_frame: false,
}]),
page_with_items(vec![PageItem::PartialTable {
para_index: 7,
control_index: 0,
start_row: 2,
end_row: 4,
is_continuation: true,
start_cut: Vec::new(),
end_cut: Vec::new(),
is_block_split: false,
start_cut_is_block: false,
row_cursor_is_nested: false,
end_row_height_override: None,
start_row_height_override: None,
straddle_row_relief: Vec::new(),
straddle_page_bands: Vec::new(),
fragment_row_heights: None,
fragment_block_frames: Vec::new(),
end_row_owns_stored_frame: false,
}]),
];
let mut paragraphs = vec![Paragraph::default(); 8];
paragraphs[7].controls = vec![Control::Table(Box::default()), Control::PageHide(hide)];
state::finalize::finalize_pages(&mut pages, &[], &None, ¶graphs);
assert!(pages[0].page_hide.is_some());
assert!(pages[1].page_hide.is_none());
}
#[test]
fn footnote_area_reserve_uses_section_shape_metrics() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let shape = FootnoteShape {
separator_margin_top: 1000,
note_spacing: 700,
raw_unknown: 900,
separator_line_width: 4,
..Default::default()
};
let note1 = Paragraph {
text: "첫 각주".to_string(),
line_segs: vec![LineSeg {
line_height: 400,
..Default::default()
}],
..Default::default()
};
let note2 = Paragraph {
text: "둘째 각주".to_string(),
line_segs: vec![LineSeg {
line_height: 600,
..Default::default()
}],
..Default::default()
};
let paras = vec![Paragraph {
text: "본문".to_string(),
line_segs: vec![LineSeg {
line_height: 400,
..Default::default()
}],
controls: vec![
Control::Footnote(Box::new(crate::model::footnote::Footnote {
number: 1,
paragraphs: vec![note1],
..Default::default()
})),
Control::Footnote(Box::new(crate::model::footnote::Footnote {
number: 2,
paragraphs: vec![note2],
..Default::default()
})),
],
..Default::default()
}];
let composed: Vec<ComposedParagraph> = paras
.iter()
.map(crate::renderer::composer::compose_paragraph)
.collect();
let run_with_shape = |shape: &FootnoteShape| {
engine.typeset_section_with_variant(
¶s,
&composed,
&styles,
&a4_page_def(),
&ColumnDef::default(),
0,
&[],
false,
Default::default(),
false,
false,
Some(shape),
None,
&std::collections::HashSet::new(),
EndnoteDeferral::None,
)
};
let result = run_with_shape(&shape);
let without_margins = run_with_shape(&FootnoteShape {
separator_margin_top: 0,
note_spacing: 0,
raw_unknown: 0,
..shape.clone()
});
let expected_delta = hwpunit_to_px(1000 + 700 + 900, DEFAULT_DPI);
let page = result.pages.first().expect("page");
let control = without_margins.pages.first().expect("대조군 page");
assert_eq!(page.footnotes.len(), 2);
assert_eq!(control.footnotes.len(), 2);
assert_eq!(result.pages.len(), without_margins.pages.len());
assert!(
(page.layout.footnote_area.height
- control.layout.footnote_area.height
- expected_delta)
.abs()
< 0.01
);
}
#[test]
fn test_typeset_single_paragraph() {
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let paras = vec![make_paragraph_with_height(400)];
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let (old_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let new_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert_pagination_match(&old_result, &new_result, "single_paragraph");
}
#[test]
fn test_typeset_page_overflow() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let mut paras: Vec<Paragraph> =
(0..100).map(|_| make_paragraph_with_height(2000)).collect();
for (idx, para) in paras.iter_mut().enumerate() {
para.text = format!("paragraph {idx}");
}
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let new_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(
new_result.pages.len(),
4,
"100개 2000-HWPUNIT 문단은 A4 4쪽"
);
let placed: Vec<_> = new_result
.pages
.iter()
.flat_map(|page| page.column_contents.iter())
.flat_map(|column| column.items.iter())
.map(PageItem::para_index)
.collect();
assert_eq!(
placed,
(0..100).collect::<Vec<_>>(),
"문단 손실·중복 없이 배치"
);
}
#[test]
fn saved_single_line_at_body_bottom_stays_on_current_page() {
let engine = TypesetEngine::with_default_dpi();
let mut styles = ResolvedStyleSet::default();
styles
.para_styles
.push(crate::renderer::style_resolver::ResolvedParaStyle {
spacing_before: 9.3,
..Default::default()
});
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
let body_height_hu =
crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
let line_height = 1200;
let line_spacing = 840;
let spacing_before_hu = crate::renderer::px_to_hwpunit(9.3, DEFAULT_DPI);
let lead_height = body_height_hu - line_height;
let lead_measured_height = lead_height - spacing_before_hu + 600;
let paras = vec![
Paragraph {
text: "lead".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height: lead_measured_height,
text_height: lead_measured_height,
..Default::default()
}],
..Default::default()
},
Paragraph {
para_shape_id: 0,
text: "tail".to_string(),
line_segs: vec![LineSeg {
vertical_pos: lead_height,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
];
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 1);
assert_eq!(result.pages[0].column_contents[0].items.len(), 2);
}
#[test]
fn two_line_tail_before_vpos_reset_stays_on_current_page_when_visible_bottom_fits() {
let engine = TypesetEngine::with_default_dpi();
let mut styles = ResolvedStyleSet::default();
styles
.para_styles
.push(crate::renderer::style_resolver::ResolvedParaStyle::default());
styles
.para_styles
.push(crate::renderer::style_resolver::ResolvedParaStyle {
spacing_before: hwpunit_to_px(2400, DEFAULT_DPI),
spacing_after: hwpunit_to_px(1400, DEFAULT_DPI),
..Default::default()
});
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
let body_height_hu =
crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
let line_height = 1200;
let line_spacing = 840;
let first_vpos = body_height_hu - 3740;
let lead_height = first_vpos - 2400;
let paras = vec![
Paragraph {
text: "lead".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height: lead_height,
text_height: lead_height,
..Default::default()
}],
..Default::default()
},
Paragraph {
para_shape_id: 1,
text: "line one\nline two".to_string(),
line_segs: vec![
LineSeg {
vertical_pos: first_vpos,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
},
LineSeg {
vertical_pos: first_vpos + line_height + line_spacing,
line_height,
text_height: line_height,
line_spacing,
text_start: 9,
..Default::default()
},
],
..Default::default()
},
Paragraph {
text: "next page".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height,
text_height: line_height,
..Default::default()
}],
..Default::default()
},
];
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 2);
assert!(matches!(
result.pages[0].column_contents[0].items.as_slice(),
[
PageItem::FullParagraph { para_index: 0 },
PageItem::FullParagraph { para_index: 1 }
]
));
assert!(matches!(
result.pages[1].column_contents[0].items.as_slice(),
[PageItem::FullParagraph { para_index: 2 }]
));
}
#[test]
fn multiline_saved_vpos_tail_does_not_split_to_near_empty_page() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
let body_height_hu =
crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
let line_height = 1200;
let line_spacing = 720;
let first_vpos = body_height_hu - (line_height + line_spacing) * 3 - line_height;
let lead_height = first_vpos + line_height;
let paras = vec![
Paragraph {
text: "lead".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height: lead_height,
text_height: lead_height,
..Default::default()
}],
..Default::default()
},
Paragraph {
text: "tail one\ntail two\ntail three\ntail four".to_string(),
line_segs: (0..4)
.map(|line_idx| LineSeg {
vertical_pos: first_vpos + (line_height + line_spacing) * line_idx,
line_height,
text_height: line_height,
line_spacing,
text_start: line_idx as u32 * 9,
..Default::default()
})
.collect(),
..Default::default()
},
Paragraph {
text: "next page".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
];
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 2);
assert!(matches!(
result.pages[0].column_contents[0].items.as_slice(),
[
PageItem::FullParagraph { para_index: 0 },
PageItem::FullParagraph { para_index: 1 }
]
));
assert!(matches!(
result.pages[1].column_contents[0].items.as_slice(),
[PageItem::FullParagraph { para_index: 2 }]
));
}
#[test]
fn page_bottom_empty_paragraph_before_vpos_reset_does_not_create_blank_page() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
let body_height_hu =
crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
let line_height = 1000;
let line_spacing = 400;
let paras = vec![
Paragraph {
text: "lead".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height: body_height_hu - 100,
text_height: body_height_hu - 100,
..Default::default()
}],
..Default::default()
},
Paragraph {
line_segs: vec![LineSeg {
vertical_pos: body_height_hu - 1200,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
Paragraph {
text: "next page".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
];
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 2);
assert!(result.hidden_empty_paras.contains(&1));
let has_empty_only_page = result.pages.iter().any(|page| {
page.column_contents.iter().any(|col| {
matches!(
col.items.as_slice(),
[PageItem::FullParagraph { para_index: 1 }]
)
})
});
assert!(!has_empty_only_page);
assert!(matches!(
result.pages[1].column_contents[0].items.as_slice(),
[PageItem::FullParagraph { para_index: 2 }]
));
}
#[test]
fn page_bottom_empty_run_before_vpos_reset_does_not_create_blank_page() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
let body_height_hu =
crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
let line_height = 1200;
let line_spacing = 720;
let paras = vec![
Paragraph {
text: "lead".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height: body_height_hu - 5000,
text_height: body_height_hu - 5000,
..Default::default()
}],
..Default::default()
},
Paragraph {
line_segs: vec![LineSeg {
vertical_pos: body_height_hu - 3800,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
Paragraph {
line_segs: vec![LineSeg {
vertical_pos: body_height_hu - 1880,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
Paragraph {
text: "next page".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height,
text_height: line_height,
line_spacing,
..Default::default()
}],
..Default::default()
},
];
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 2);
assert!(result.hidden_empty_paras.contains(&1));
assert!(result.hidden_empty_paras.contains(&2));
let has_empty_only_page = result.pages.iter().any(|page| {
page.column_contents.iter().any(|col| {
matches!(
col.items.as_slice(),
[PageItem::FullParagraph { para_index: 1 }]
| [PageItem::FullParagraph { para_index: 2 }]
| [
PageItem::FullParagraph { para_index: 1 },
PageItem::FullParagraph { para_index: 2 }
]
)
})
});
assert!(!has_empty_only_page);
assert!(matches!(
result.pages[1].column_contents[0].items.as_slice(),
[PageItem::FullParagraph { para_index: 3 }]
));
}
#[test]
fn saved_tac_table_line_at_body_bottom_stays_on_current_page() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
let body_height_hu =
crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
let table_height = 10_072;
let table_vpos = body_height_hu - table_height;
let lead_height = table_vpos + 900;
let paras = vec![
Paragraph {
text: "lead".to_string(),
line_segs: vec![LineSeg {
vertical_pos: 0,
line_height: lead_height,
text_height: lead_height,
..Default::default()
}],
..Default::default()
},
Paragraph {
controls: vec![Control::Table(Box::new(crate::model::table::Table {
attr: 1,
row_count: 3,
col_count: 3,
common: crate::model::shape::CommonObjAttr {
treat_as_char: true,
text_wrap: crate::model::shape::TextWrap::TopAndBottom,
height: table_height as u32,
..Default::default()
},
..Default::default()
}))],
line_segs: vec![LineSeg {
vertical_pos: table_vpos,
line_height: table_height,
text_height: table_height,
line_spacing: 120,
..Default::default()
}],
..Default::default()
},
];
let composed: Vec<ComposedParagraph> = Vec::new();
let result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(result.pages.len(), 1);
assert!(matches!(
result.pages[0].column_contents[0].items.as_slice(),
[
PageItem::FullParagraph { para_index: 0 },
PageItem::Table { para_index: 1, .. }
]
));
}
#[test]
fn test_measure_endnote_advance_side_effect_free() {
use crate::renderer::composer::compose_paragraph;
let para = Paragraph {
text: "각주 측정 격리 회귀 가드 문장".to_string(),
line_segs: vec![LineSeg {
line_height: 1000,
baseline_distance: 850,
..Default::default()
}],
..Default::default()
};
let composed = compose_paragraph(¶);
let styles = ResolvedStyleSet::default();
let item = PageItem::FullParagraph { para_index: 900 };
let (en_col_w, available, y_start) = (280.0_f64, 900.0_f64, 100.0_f64);
let engine = TypesetEngine::new(96.0);
let first = engine.measure_endnote_para_advance(
¶, &composed, &styles, en_col_w, available, y_start, &item, 0, 900,
);
assert!(
first.is_finite() && first > 0.0,
"advance must be positive finite: {first}",
);
for _ in 0..5 {
let v = engine.measure_endnote_para_advance(
¶, &composed, &styles, en_col_w, available, y_start, &item, 0, 900,
);
assert_eq!(v, first, "repeat call drifted — scratch 상태 누적 누수");
}
let engine2 = TypesetEngine::new(96.0);
let other = engine2.measure_endnote_para_advance(
¶, &composed, &styles, en_col_w, available, y_start, &item, 0, 900,
);
assert_eq!(other, first, "independent engine differs — 전역 상태 누수");
}
#[test]
fn test_typeset_line_split() {
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let paras = vec![Paragraph {
line_segs: (0..50)
.map(|_| LineSeg {
line_height: 1800,
line_spacing: 200,
..Default::default()
})
.collect(),
..Default::default()
}];
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let (old_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let new_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert_pagination_match(&old_result, &new_result, "line_split");
}
#[test]
fn test_typeset_mixed_paragraphs() {
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let paras: Vec<Paragraph> = vec![
make_paragraph_with_height(400),
make_paragraph_with_height(10000), make_paragraph_with_height(400),
make_paragraph_with_height(800),
make_paragraph_with_height(20000), make_paragraph_with_height(400),
];
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let (old_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let new_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert_pagination_match(&old_result, &new_result, "mixed_paragraphs");
}
#[test]
fn test_typeset_page_break() {
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let paras = vec![
make_paragraph_with_height(400),
{
let mut p = make_paragraph_with_height(400);
p.column_type = ColumnBreakType::Page;
p
},
make_paragraph_with_height(400),
];
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let (old_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let new_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert_pagination_match(&old_result, &new_result, "page_break");
assert_eq!(new_result.pages.len(), 2, "쪽 나누기로 2페이지");
}
#[test]
fn test_typeset_force_break_before_hint() {
let engine = TypesetEngine::with_default_dpi();
let styles = ResolvedStyleSet::default();
let mut paras = vec![
make_paragraph_with_height(400),
make_paragraph_with_height(400),
make_paragraph_with_height(400),
];
for (idx, para) in paras.iter_mut().enumerate() {
para.text = format!("paragraph {idx}");
}
let composed: Vec<ComposedParagraph> = Vec::new();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let baseline = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&std::collections::HashSet::new(),
);
assert_eq!(baseline.pages.len(), 1, "hint 없으면 3문단 모두 1페이지");
let mut hint = std::collections::HashSet::new();
hint.insert(1usize);
let reflowed = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&[],
false,
&hint,
);
assert_eq!(reflowed.pages.len(), 2, "para1 force-break 로 2페이지");
let page0_paras: Vec<usize> = reflowed.pages[0]
.column_contents
.iter()
.flat_map(|cc| cc.items.iter().map(|it| it.para_index()))
.collect();
let page1_paras: Vec<usize> = reflowed.pages[1]
.column_contents
.iter()
.flat_map(|cc| cc.items.iter().map(|it| it.para_index()))
.collect();
assert_eq!(page0_paras, vec![0], "1페이지엔 para0 만");
assert_eq!(page1_paras, vec![1, 2], "2페이지엔 para1,2");
}
fn compare_with_hwp_file(path: &str) {
let data = match std::fs::read(path) {
Ok(d) => d,
Err(_) => {
eprintln!("skip: {} not found", path);
return;
}
};
let doc = match crate::document_core::DocumentCore::from_bytes(&data) {
Ok(d) => d,
Err(e) => {
eprintln!("skip: {} parse error: {}", path, e);
return;
}
};
let engine = TypesetEngine::with_default_dpi();
for (sec_idx, section) in doc.document.sections.iter().enumerate() {
let composed = &doc.composed[sec_idx];
let measured_tables = &doc.measured_tables[sec_idx];
let column_def =
crate::document_core::DocumentCore::find_initial_column_def(§ion.paragraphs);
let has_tables = section
.paragraphs
.iter()
.any(|p| p.controls.iter().any(|c| matches!(c, Control::Table(_))));
let new_result = engine.typeset_section(
§ion.paragraphs,
composed,
&doc.styles,
§ion.section_def.page_def,
&column_def,
sec_idx,
measured_tables,
section.section_def.hide_empty_line,
&std::collections::HashSet::new(),
);
let old_result = &doc.pagination[sec_idx];
let label = format!("{} sec{}", path, sec_idx);
if has_tables {
if old_result.pages.len() != new_result.pages.len() {
eprintln!(
"WARN {}: 표 포함 구역 페이지 수 차이 (old={}, new={}) — Phase 2에서 해결",
label,
old_result.pages.len(),
new_result.pages.len(),
);
}
} else {
assert_eq!(
old_result.pages.len(),
new_result.pages.len(),
"{}: 페이지 수 불일치 (old={}, new={})",
label,
old_result.pages.len(),
new_result.pages.len(),
);
for (pi, (old_page, new_page)) in old_result
.pages
.iter()
.zip(new_result.pages.iter())
.enumerate()
{
assert_eq!(
old_page.column_contents.len(),
new_page.column_contents.len(),
"{}: p{} 단 수 불일치",
label,
pi,
);
}
}
}
}
#[test]
fn test_typeset_vs_paginator_p222() {
compare_with_hwp_file("samples/p222.hwp");
}
#[test]
fn test_typeset_vs_paginator_hongbo() {
compare_with_hwp_file("samples/20250130-hongbo.hwp");
}
#[test]
fn test_typeset_vs_paginator_biz_plan() {
compare_with_hwp_file("samples/biz_plan.hwp");
}
#[test]
fn test_typeset_703_behind_text_table_no_flow_advance() {
use crate::model::shape::TextWrap;
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let composed: Vec<ComposedParagraph> = Vec::new();
let mut table = crate::model::table::Table {
row_count: 1,
col_count: 1,
cells: vec![crate::model::table::Cell {
col: 0,
row: 0,
col_span: 1,
row_span: 1,
width: 51974,
height: 60000,
paragraphs: vec![Paragraph::default()],
..Default::default()
}],
..Default::default()
};
table.common.text_wrap = TextWrap::BehindText;
table.common.treat_as_char = false;
table.common.width = 51974;
table.common.height = 60000;
let host_para = Paragraph {
line_segs: vec![LineSeg {
line_height: 1000,
line_spacing: 600,
..Default::default()
}],
controls: vec![crate::model::control::Control::Table(Box::new(table))],
..Default::default()
};
let mut paras = vec![host_para];
for _ in 0..5 {
paras.push(make_paragraph_with_height(1000));
}
let (paginator_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let typeset_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert_eq!(
paginator_result.pages.len(),
1,
"[reference] BehindText 표 + 5 후속 paragraph 는 paginator 에서 1 페이지에 들어가야 함",
);
assert_eq!(
typeset_result.pages.len(),
1,
"[BUG #703] typeset 도 1 페이지여야 함. 결함 시 BehindText 표 height ≈800 px 가 \
cur_h 에 가산되어 후속 paragraph 가 다음 페이지로 밀림 (RED)",
);
}
#[test]
fn test_typeset_1995_multi_fullpage_images_split_pages() {
use crate::model::shape::TextWrap;
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let composed: Vec<ComposedParagraph> = Vec::new();
let make_pic = || {
let mut pic = crate::model::image::Picture::default();
pic.common.treat_as_char = false;
pic.common.text_wrap = TextWrap::Square;
pic.common.width = 51974;
pic.common.height = 60000;
crate::model::control::Control::Picture(Box::new(pic))
};
let host_para = Paragraph {
line_segs: vec![LineSeg {
line_height: 1000,
line_spacing: 600,
..Default::default()
}],
controls: vec![make_pic(), make_pic(), make_pic()],
..Default::default()
};
let paras = vec![host_para];
let (_paginator_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let typeset_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert!(
typeset_result.pages.len() >= 3,
"[#1995] 전면 non-TAC 이미지 3장은 각각 한 페이지에 단독 배치되어야 함(>= 3 페이지). \
실제 {} 페이지 — 미수정 시 한 앵커에 스택",
typeset_result.pages.len(),
);
}
#[test]
fn test_typeset_4770_stored_line_beside_pile_keeps_stack_on_anchor_page() {
use crate::model::shape::TextWrap;
let engine = TypesetEngine::with_default_dpi();
let paginator = Paginator::with_default_dpi();
let styles = ResolvedStyleSet::default();
let page_def = a4_page_def();
let col_def = ColumnDef::default();
let composed: Vec<ComposedParagraph> = Vec::new();
let make_pic = || {
let mut pic = crate::model::image::Picture::default();
pic.common.treat_as_char = false;
pic.common.text_wrap = TextWrap::Square;
pic.common.width = 51974;
pic.common.height = 60000;
crate::model::control::Control::Picture(Box::new(pic))
};
let host_para = Paragraph {
line_segs: vec![LineSeg {
line_height: 1000,
line_spacing: 600,
column_start: 51974,
segment_width: 3480,
..Default::default()
}],
controls: vec![make_pic(), make_pic(), make_pic()],
..Default::default()
};
let paras = vec![host_para];
let (_paginator_result, measured) =
paginator.paginate(¶s, &composed, &styles, &page_def, &col_def, 0);
let typeset_result = engine.typeset_section(
¶s,
&composed,
&styles,
&page_def,
&col_def,
0,
&measured.tables,
false,
&std::collections::HashSet::new(),
);
assert_eq!(
typeset_result.pages.len(),
1,
"[#4770] 저장 줄이 그림 옆에 끼인(cs ≥ 그림 폭) 스택은 앵커 쪽 1 페이지에 \
남아야 함. 실제 {} 페이지 — 낱장 분산이 오발동",
typeset_result.pages.len(),
);
}
#[test]
fn test_4770_anchor_pile_contract_requires_square_stack_and_page_bottom() {
use crate::document_core::queries::rendering::body_pile_stays_on_anchor_page;
use crate::model::page::PageAreas;
use crate::model::shape::TextWrap;
let page_def = a4_page_def();
let body_area = PageAreas::from_page_def(&page_def).body_area;
let make_para = |text_wrap| {
let make_pic = || {
let mut pic = crate::model::image::Picture::default();
pic.common.treat_as_char = false;
pic.common.text_wrap = text_wrap;
pic.common.allow_overlap = false;
pic.common.width = 51974;
pic.common.height = 60000;
crate::model::control::Control::Picture(Box::new(pic))
};
Paragraph {
line_segs: vec![LineSeg {
vertical_pos: body_area.bottom - 60000,
column_start: 51974,
segment_width: 3480,
..Default::default()
}],
controls: vec![make_pic(), make_pic(), make_pic()],
..Default::default()
}
};
assert!(
body_pile_stays_on_anchor_page(&make_para(TextWrap::Square), 30000, body_area.bottom),
"페이지 상단 기준 vpos가 본문 하단에 정확히 닿는 Square 스택은 앵커 쪽에 남아야 함"
);
assert!(
!body_pile_stays_on_anchor_page(
&make_para(TextWrap::TopAndBottom),
30000,
body_area.bottom,
),
"TopAndBottom 전면 그림은 cs/vpos가 같아도 #1995 낱장 배치를 억제하면 안 됨"
);
}
#[test]
fn issue_3821_square_picture_wrap_band_is_bounded_and_contiguous() {
let seg = |vertical_pos, column_start, segment_width| LineSeg {
vertical_pos,
column_start,
segment_width,
..Default::default()
};
let paragraphs = vec![
Paragraph {
line_segs: vec![seg(-2000, 0, 45352), seg(0, 0, 25139), seg(2000, 0, 25139)],
..Default::default()
},
Paragraph {
line_segs: vec![seg(4000, 0, 25139)],
..Default::default()
},
Paragraph {
line_segs: vec![seg(4600, 0, 25139)],
..Default::default()
},
Paragraph {
line_segs: vec![seg(5200, 0, 25139)],
..Default::default()
},
Paragraph {
line_segs: vec![seg(21800, 0, 25139)],
..Default::default()
},
Paragraph {
line_segs: vec![seg(23800, 0, 25139)],
..Default::default()
},
];
assert_eq!(
controls::deferred_picture::square_picture_wrap_band_target_paragraphs(
¶graphs,
0,
0,
23231,
0,
25139,
),
vec![0, 1, 2, 3, 4],
"actual image band must include p1693..p1697 and stop before p1698",
);
}
}
fn title_mark_prefix_advance(para: &Paragraph, ctrl_idx: usize, dpi: f64) -> Option<f64> {
if !para.text.is_empty()
|| !para.title_marks.iter().any(|mark| mark.char_idx == 0)
|| para.stored_text_partition_is_dirty()
|| para.cell_format_vpos_dirty
{
return None;
}
let owner = crate::renderer::composer::control_slot_line_index(para, ctrl_idx)
.filter(|&line| line > 0)?;
let rows = para.line_segs.get(..=owner)?;
if rows.iter().any(|seg| {
is_synthetic_line_seg(seg)
|| seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
}) || !rows
.windows(2)
.all(|pair| pair[1].vertical_pos > pair[0].vertical_pos)
{
return None;
}
Some(hwpunit_to_px(
rows[owner].vertical_pos - rows[0].vertical_pos,
dpi,
))
}