pub fn compose_section(section: &Section) -> Vec<ComposedParagraph> {
section
.paragraphs
.iter()
.map(|para| {
let mut composed = compose_paragraph(para);
auto_number_projection::project(&mut composed, para);
composed
})
.collect()
}
pub(crate) fn compose_section_with_horizontal_shaping(
section: &Section,
styles: &ResolvedStyleSet,
) -> Vec<ComposedParagraph> {
match try_compose_section_with_horizontal_shaping(section, styles, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn try_compose_section_with_horizontal_shaping<S: crate::storage::Storage>(
section: &Section,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<Vec<ComposedParagraph>, S::Error> {
let _tabs = styles.section_tab_scope(
section.section_def.default_tab_spacing,
styles.resolved_dpi.unwrap_or(crate::renderer::DEFAULT_DPI),
);
let mut paragraphs = storage.vec(section.paragraphs.len())?;
for paragraph in §ion.paragraphs {
paragraphs.push(try_compose_paragraph_with_horizontal_shaping(
paragraph, styles, storage,
)?);
}
Ok(paragraphs)
}
fn try_synthesize_marker_paragraph<S: crate::storage::Storage>(
para: &Paragraph,
storage: &S,
) -> Result<Option<Paragraph>, S::Error> {
fn needs_synthesized_inline_marker(ctrl: &Control) -> bool {
is_render_inline_control(ctrl)
}
let inline_ctrl_count = para
.controls
.iter()
.filter(|ctrl| needs_synthesized_inline_marker(ctrl))
.count();
if inline_ctrl_count == 0 {
return Ok(None);
}
let text_has_only_layout_space = para
.text
.chars()
.all(|ch| matches!(ch, '\n' | '\r' | '\t' | ' ' | '\u{2007}'));
let controls_are_tac_objects = para.controls.iter().all(|ctrl| {
matches!(
ctrl,
Control::Equation(eq) if eq.common.treat_as_char
) || matches!(
ctrl,
Control::Picture(_) | Control::Shape(_) | Control::Table(_) | Control::Form(_)
)
});
if text_has_only_layout_space && controls_are_tac_objects {
return Ok(None);
}
let existing_markers = para.text.chars().filter(|c| *c == '\u{FFFC}').count();
if existing_markers >= inline_ctrl_count {
return Ok(None);
}
let offsets = ¶.char_offsets;
let first_off = offsets.first().copied().unwrap_or(0) as usize;
let n_leading = first_off / 8;
if n_leading < 2 || inline_ctrl_count < 3 {
return Ok(None);
}
let raw_positions = para.try_control_text_positions(storage)?;
let raw_inline_positions: Vec<usize> = storage.collect(
para.controls
.iter()
.enumerate()
.filter(|(_, ctrl)| needs_synthesized_inline_marker(ctrl))
.filter_map(|(i, _)| raw_positions.get(i).copied()),
)?;
if raw_inline_positions.iter().any(|pos| *pos > 0) {
return Ok(None);
}
let chars: Vec<char> = storage.collect(para.text.chars())?;
let mut new_text = storage.string("")?;
let mut new_offsets: Vec<u32> = storage.vec(
para.char_offsets
.len()
.saturating_add(inline_ctrl_count - existing_markers),
)?;
let mut literal_figure_spaces = Vec::new();
for i in 0..n_leading {
storage.push(&mut new_offsets, (i * 8) as u32)?;
storage.push_char(&mut new_text, '\u{FFFC}')?;
}
for (i, &off) in offsets.iter().enumerate() {
let ch = chars.get(i).copied().unwrap_or(' ');
if para.literal_figure_spaces.binary_search(&i).is_ok() {
storage.push(&mut literal_figure_spaces, new_offsets.len())?;
}
storage.push(&mut new_offsets, off)?;
storage.push_char(&mut new_text, ch)?;
let char_width: u32 = if (ch as u32) > 0xFFFF { 2 } else { 1 };
let next_off = if i + 1 < offsets.len() {
offsets[i + 1] as usize
} else {
continue;
};
let gap = next_off
.saturating_sub(off as usize)
.saturating_sub(char_width as usize);
let n_ctrls_between = gap / 8;
for k in 0..n_ctrls_between {
storage.push(
&mut new_offsets,
(off as usize + char_width as usize + k * 8) as u32,
)?;
storage.push_char(&mut new_text, '\u{FFFC}')?;
}
}
let added_so_far = new_text.chars().filter(|c| *c == '\u{FFFC}').count();
let still_needed = inline_ctrl_count.saturating_sub(added_so_far);
if still_needed > 0 {
let last_off = offsets.last().copied().unwrap_or(0) as usize;
let last_ch = chars.last().copied().unwrap_or(' ');
let last_w: usize = if (last_ch as u32) > 0xFFFF { 2 } else { 1 };
let mut next_pos = last_off + last_w;
for _ in 0..still_needed {
storage.push(&mut new_offsets, next_pos as u32)?;
storage.push_char(&mut new_text, '\u{FFFC}')?;
next_pos += 8;
}
}
let mut synth = storage.clone_paragraph(para)?;
synth.text = new_text;
synth.char_offsets = new_offsets;
synth.literal_figure_spaces = literal_figure_spaces;
Ok(Some(synth))
}
pub fn compose_paragraph(para: &Paragraph) -> ComposedParagraph {
compose_paragraph_scoped(para, false, None)
}
pub(crate) fn compose_paragraph_in_context(
para: &Paragraph,
styles: &ResolvedStyleSet,
) -> ComposedParagraph {
compose_paragraph_scoped(para, styles.supplemental_metrics.is_some(), Some(styles))
}
pub(crate) fn compose_paragraph_in_context_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<ComposedParagraph, S::Error> {
try_compose_paragraph_scoped(
para,
styles.supplemental_metrics.is_some(),
Some(styles),
storage,
)
}
pub(crate) fn compose_paragraph_for_metric_requests(para: &Paragraph) -> ComposedParagraph {
compose_paragraph_scoped(para, true, None)
}
fn compose_paragraph_scoped(
para: &Paragraph,
protect_metrics: bool,
metric_styles: Option<&ResolvedStyleSet>,
) -> ComposedParagraph {
match try_compose_paragraph_scoped(
para,
protect_metrics,
metric_styles,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn try_compose_paragraph_scoped<S: crate::storage::Storage>(
para: &Paragraph,
protect_metrics: bool,
metric_styles: Option<&ResolvedStyleSet>,
storage: &S,
) -> Result<ComposedParagraph, S::Error> {
try_compose_paragraph_scoped_with_frame_tables(
para, protect_metrics, metric_styles, &[], storage,
)
}
fn try_compose_paragraph_scoped_with_frame_tables<S: crate::storage::Storage>(
para: &Paragraph,
protect_metrics: bool,
metric_styles: Option<&ResolvedStyleSet>,
frame_tables: &[(usize, u32)],
storage: &S,
) -> Result<ComposedParagraph, S::Error> {
let synth_para = try_synthesize_marker_paragraph(para, storage)?;
let para = synth_para.as_ref().unwrap_or(para);
let mut lines = try_compose_lines(para, storage)?;
if let Some(styles) = metric_styles {
punctuation_slots::try_resolve_run_slots(
&mut lines,
styles,
crate::renderer::para_has_no_stored_line_segs(para),
storage,
)?;
}
let inline_controls = try_identify_inline_controls(para, storage)?;
let tac_positions = try_find_render_inline_control_positions(para, storage)?;
let seg_width = para.line_segs.first().map(|s| s.segment_width).unwrap_or(0);
let tac_controls: Vec<(usize, i32, usize)> =
storage.collect(para.controls.iter().enumerate().filter_map(|(i, ctrl)| {
let pos = *tac_positions.get(i)?;
match ctrl {
Control::Picture(p) if p.common.treat_as_char => {
Some((pos, inline_picture_size_hu(p).0, i))
}
Control::Shape(s) if s.common().treat_as_char => {
Some((pos, s.common().width as i32, i))
}
Control::Equation(eq) if eq.common.treat_as_char => {
Some((
pos,
crate::renderer::equation::inline_advance_width_hwp(eq),
i,
))
}
Control::Form(f) if f.common.treat_as_char => Some((pos, f.width as i32, i)),
Control::Table(t)
if t.common.treat_as_char
&& (frame_tables.iter().any(|&(owner, _)| owner == i)
|| super::height_measurer::is_tac_table_inline_in_para(
t, seg_width, para,
)) =>
{
let table_width: u32 = t.flow_width_hu();
Some((pos, table_width as i32, i))
}
_ => None,
}
}))?;
let footnote_positions: Vec<(usize, u16, usize)> =
storage.collect(para.controls.iter().enumerate().filter_map(|(i, ctrl)| {
let pos = *tac_positions.get(i)?;
match ctrl {
Control::Footnote(fn_) => Some((pos, fn_.number, i)),
Control::Endnote(en) => Some((pos, en.number, i)),
_ => None,
}
}))?;
let block_tac_split_pos = para
.controls
.iter()
.enumerate()
.find_map(|(i, ctrl)| match ctrl {
Control::Table(t)
if t.common.treat_as_char
&& !tac_controls.iter().any(|(_, _, ci)| *ci == i)
&& !super::height_measurer::is_tac_table_inline_in_para(t, seg_width, para) =>
{
tac_positions.get(i).copied()
}
_ => None,
});
if let Some(ctrl_pos) = block_tac_split_pos {
let total_chars = para.text.chars().count();
let chars: Vec<char> = storage.collect(para.text.chars())?;
let line_end = |lines: &[ComposedLine], idx: usize| {
lines
.get(idx + 1)
.map(|l| l.char_start)
.unwrap_or(total_chars)
};
let host_line = (0..lines.len()).find(|&i| {
let end = line_end(&lines, i).max(lines[i].char_start + 1);
let end_inclusive = if i + 1 == lines.len() { end + 1 } else { end };
lines[i].char_start <= ctrl_pos && ctrl_pos < end_inclusive
});
if let Some(li) = host_line {
let start = lines[li].char_start.min(total_chars);
let end = line_end(&lines, li).min(total_chars);
let is_visible_glyph = |ch: char| {
!ch.is_whitespace()
&& ch > '\u{001F}'
&& ch != '\u{FFFC}'
&& !('\u{E000}'..='\u{F8FF}').contains(&ch)
&& (ch as u32) < 0xF0000
};
let line_has_visible_text = chars[start..end].iter().any(|&c| is_visible_glyph(c));
if line_has_visible_text {
let table_line = ComposedLine {
runs: Vec::new(),
line_height: lines[li].line_height,
baseline_distance: lines[li].baseline_distance,
segment_width: lines[li].segment_width,
column_start: lines[li].column_start,
line_spacing: lines[li].line_spacing,
has_line_break: true,
char_start: lines[li].char_start,
};
lines[li].line_height = 400;
lines[li].baseline_distance = 320;
storage.reserve(&mut lines, 1)?;
lines.insert(li, table_line);
}
}
}
let mut composed = ComposedParagraph {
lines,
para_style_id: para.para_shape_id,
inline_controls,
numbering_text: None,
tac_controls,
footnote_positions,
tab_extended: if super::para_has_no_stored_line_segs(para) {
Vec::new()
} else {
storage.copy_slice(¶.tab_extended)?
},
horizontal_shaping: None,
frame_geometry: None,
};
if let Some(styles) = metric_styles {
equation_line_metrics::try_refresh_equation_rows(&mut composed, para, styles, storage)?;
empty_line_metrics::refresh_with_storage(&mut composed, para, styles, storage)?;
inline_picture_metrics::refresh_picture_rows_with_storage(&mut composed, para, styles, storage)?;
}
supplemental_clusters::preserve_literal_spaces_with_storage(&mut composed, ¶.literal_figure_spaces, storage)?;
try_inject_char_overlap_text(&mut composed, para, metric_styles, storage)?;
try_convert_pua_enclosed_numbers(&mut composed, storage)?;
let soft_hyphen_control = para.control_mask & (1u32 << 0x0018) != 0;
try_convert_pua_display_text(&mut composed, soft_hyphen_control, metric_styles, storage)?;
if protect_metrics {
supplemental_clusters::preserve_boundaries(&mut composed, ¶.text, metric_styles);
}
mapped_symbol_fonts::try_split_mapped_symbol_font_runs(&mut composed, storage)?;
resolved_fields::try_apply(para, &mut composed, storage)?;
if let Some(styles) = metric_styles {
conjoining_jamo::split_runs_with_storage(&mut composed, styles, storage)?;
}
storage.bytes(0)?;
Ok(composed)
}
pub(crate) fn compose_paragraph_with_horizontal_shaping(
para: &Paragraph,
styles: &ResolvedStyleSet,
) -> ComposedParagraph {
match try_compose_paragraph_with_horizontal_shaping(para, styles, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn try_compose_paragraph_with_horizontal_shaping<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<ComposedParagraph, S::Error> {
let mut composed = try_compose_paragraph_scoped(
para,
styles.supplemental_metrics.is_some(),
Some(styles),
storage,
)?;
auto_number_projection::project(&mut composed, para);
composed.horizontal_shaping =
line_breaking::compose_horizontal_shaping_handoff(para, &composed, styles);
storage.bytes(0)?;
Ok(composed)
}
pub(crate) fn first_text_line(composed: &ComposedParagraph) -> Option<usize> {
composed.lines.iter().position(|line| {
line.runs
.iter()
.any(|r| r.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}'))
})
}
pub(crate) fn owned_rowbreak_tac_height(para: &Paragraph, control_index: usize) -> Option<i32> {
let Control::Table(table) = para.controls.get(control_index)? else {
return None;
};
if !table.common.treat_as_char
|| !matches!(
table.page_break,
crate::model::table::TablePageBreak::RowBreak
)
{
return None;
}
let seg = para
.line_segs
.get(control_line_seg_index(para, control_index)?)?;
let is_current_row = seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0;
if table.row_count <= 1 && !is_current_row {
return None;
}
(is_current_row || i64::from(seg.line_height) >= i64::from(table.common.height))
.then_some(seg.line_height)
}
pub(crate) fn tac_host_trailing_spacing(
para: &Paragraph,
control_index: usize,
seg: &LineSeg,
hwpx_stored_layout: bool,
native_stored_layout: bool,
dpi: f64,
) -> f64 {
let spacing = crate::renderer::hwpunit_to_px(seg.line_spacing, dpi);
if spacing <= 0.0 {
return spacing;
}
let current_owned_row = hwpx_stored_layout
&& para.line_segs.len() == 1
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
&& owned_rowbreak_tac_height(para, control_index).is_some();
let stored_successor_owns_full_gap = native_stored_layout
&& !para.stored_text_partition_is_dirty()
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& para.line_segs.windows(2).any(|pair| {
std::ptr::eq(&pair[0], seg)
&& pair[1].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& pair[1].text_start > seg.text_start
&& seg
.vertical_pos
.checked_add(seg.line_height)
.and_then(|end| end.checked_add(seg.line_spacing))
== Some(pair[1].vertical_pos)
});
if stored_successor_owns_full_gap {
spacing
} else if current_owned_row
|| (native_stored_layout
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& !para.stored_text_partition_is_dirty())
{
spacing / 2.0
} else {
spacing
}
}
fn successor_lacks_stored_text_axis(para: &Paragraph) -> bool {
para.stored_text_partition_is_dirty()
|| crate::renderer::para_has_no_stored_line_segs(para)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn tac_host_trailing_spacing_at_boundary(
para: &Paragraph,
next_para: Option<&Paragraph>,
control_index: usize,
seg: &LineSeg,
hwpx_stored_layout: bool,
native_stored_layout: bool,
dpi: f64,
) -> f64 {
if native_stored_layout
&& !para.stored_text_partition_is_dirty()
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& para
.line_segs
.last()
.is_some_and(|last| std::ptr::eq(last, seg))
&& next_para.is_some_and(successor_lacks_stored_text_axis)
{
crate::renderer::hwpunit_to_px(seg.line_spacing, dpi)
} else {
tac_host_trailing_spacing(
para,
control_index,
seg,
hwpx_stored_layout,
native_stored_layout,
dpi,
)
}
}
pub(crate) fn tac_successor_uses_reflow_spacing(
para: &Paragraph,
next_para: Option<&Paragraph>,
seg: &LineSeg,
profile: crate::model::provenance::LayoutCompatibilityProfile,
) -> bool {
profile.hwp5_stored_pagination_layout()
&& !profile.session_edited()
&& !para.stored_text_partition_is_dirty()
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& para
.line_segs
.last()
.is_some_and(|last| std::ptr::eq(last, seg))
&& next_para.is_some_and(|next| {
next.controls.is_empty() && successor_lacks_stored_text_axis(next)
})
}
pub(crate) fn current_tac_local_successor_advance_hu(
para: &Paragraph,
next_para: Option<&Paragraph>,
current_spacing_after_px: f64,
next_spacing_before_px: f64,
seg: &LineSeg,
profile: crate::model::provenance::LayoutCompatibilityProfile,
dpi: f64,
) -> Option<i32> {
if !profile.hwpx_stored_layout()
|| profile.session_edited()
|| para.stored_text_partition_is_dirty()
|| para.cell_format_vpos_dirty
|| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
|| seg.line_spacing < 0
|| para
.text
.chars()
.any(|ch| ch > '\u{001f}' && ch != '\u{fffc}' && !ch.is_whitespace())
{
return None;
}
let [line] = para.line_segs.as_slice() else {
return None;
};
let [Control::Table(table)] = para.controls.as_slice() else {
return None;
};
if !std::ptr::eq(line, seg)
|| table.caption.is_some()
|| owned_rowbreak_tac_height(para, 0) != Some(seg.line_height)
|| i64::from(seg.line_height)
!= i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom)
{
return None;
}
let next = next_para?;
if next.stored_text_partition_is_dirty()
|| next.cell_format_vpos_dirty
|| !next.controls.is_empty()
|| next.raw_break_type != 0
|| next.column_type != crate::model::paragraph::ColumnBreakType::None
{
return None;
}
let first = next.line_segs.first()?;
if first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
|| first.vertical_pos < 0
|| first.vertical_pos >= seg.vertical_pos
{
return None;
}
let unit = hwpunit_to_px(1, dpi);
let after = (current_spacing_after_px / unit).round() as i32;
let before = (next_spacing_before_px / unit).round() as i32;
let end = seg
.line_height
.checked_add(seg.line_spacing)?
.checked_add(after)?;
(end.checked_add(before)? == first.vertical_pos).then_some(end)
}
pub(crate) fn tac_next_line_full_spacing(
para: &Paragraph,
next_para: Option<&Paragraph>,
current_spacing_after_px: f64,
next_spacing_before_px: f64,
seg: &LineSeg,
profile: crate::model::provenance::LayoutCompatibilityProfile,
dpi: f64,
) -> bool {
if tac_successor_uses_reflow_spacing(para, next_para, seg, profile) {
return true;
}
let next_spacing_before_hu = (next_spacing_before_px / hwpunit_to_px(1, dpi)).round() as i32;
let current_spacing_after_hu =
(current_spacing_after_px / hwpunit_to_px(1, dpi)).round() as i32;
let current_owned_row = profile.hwpx_stored_layout()
&& para.line_segs.len() == 1
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
&& para
.controls
.iter()
.enumerate()
.any(|(ci, _)| owned_rowbreak_tac_height(para, ci).is_some());
let stored_host = (profile.hwp5_stored_pagination_layout() || profile.hwpx_stored_layout())
&& !para.stored_text_partition_is_dirty()
&& !para.cell_format_vpos_dirty
&& seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0;
if stored_host
&& !para.cell_format_vpos_dirty
&& seg.vertical_pos >= 0
&& seg.line_height > 0
&& seg.line_spacing > 0
&& para.line_segs.windows(2).any(|pair| {
std::ptr::eq(&pair[0], seg)
&& pair[1].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& pair[1].line_height > 0
&& i64::from(seg.vertical_pos)
+ i64::from(seg.line_height)
+ i64::from(seg.line_spacing)
== i64::from(pair[1].vertical_pos)
})
{
return true;
}
(stored_host || current_owned_row)
&& para
.line_segs
.last()
.is_some_and(|last| std::ptr::eq(last, seg))
&& next_para.is_some_and(|next| {
(current_owned_row || !next.stored_text_partition_is_dirty())
&& (next.line_segs.is_empty()
|| next.line_segs.first().is_some_and(|first| {
(current_owned_row
|| (first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& !next.cell_format_vpos_dirty))
&& (stored_tac_successor_delta_hu(
para,
seg,
first,
current_spacing_after_hu.saturating_add(next_spacing_before_hu),
)
.is_some_and(|delta| {
seg.line_height
.checked_add(seg.line_spacing)
.and_then(|advance| {
advance.checked_add(current_spacing_after_hu)
})
.and_then(|advance| advance.checked_add(next_spacing_before_hu))
== Some(delta)
})
|| crate::renderer::float_placement::restarted_tac::restarted_tac_line_advance(
para,
next,
current_spacing_after_px,
next_spacing_before_px,
dpi,
).is_some())
}))
})
}
pub(crate) fn stored_tac_successor_delta_hu(
para: &Paragraph,
seg: &LineSeg,
successor: &LineSeg,
paragraph_spacing_hu: i32,
) -> Option<i32> {
let closing_advance = seg
.line_height
.checked_add(seg.line_spacing)?
.checked_add(paragraph_spacing_hu)?;
let reset_closes_owned_line = successor.vertical_pos < seg.vertical_pos
&& successor.vertical_pos == closing_advance
&& para.line_segs.len() == 1
&& !para.cell_format_vpos_dirty
&& successor.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& stored_first_tac_line(para).is_some_and(|first| std::ptr::eq(first, seg))
&& para
.controls
.iter()
.filter(|control| matches!(control, Control::Table(_)))
.count()
== 1
&& !para.controls.iter().any(|control| {
matches!(
control,
Control::Picture(_) | Control::Shape(_) | Control::Equation(_)
)
});
if reset_closes_owned_line {
Some(successor.vertical_pos)
} else {
successor.vertical_pos.checked_sub(seg.vertical_pos)
}
}