fn estimate_regenerated_line_text_width(
text: &str,
style: &TextStyle,
regenerated_line_space_metric: bool,
) -> f64 {
let measured = estimate_text_width_unrounded(text, style);
if !regenerated_line_space_metric {
return measured;
}
let Some(regenerated_space_width) = hancom_regenerated_space_width(style) else {
return measured;
};
let stored_space_width = estimate_text_width_unrounded(" ", style);
measured
+ text.chars().filter(|&ch| ch == ' ').count() as f64
* (regenerated_space_width - stored_space_width)
}
fn regenerated_half_space_width(style: &TextStyle) -> f64 {
let font_size = style.font_size.max(0.0);
let ratio = if style.ratio > 0.0 { style.ratio } else { 1.0 };
let base = font_size * style.font_space_em.unwrap_or(0.5) * ratio;
let tracking = if font_size > 0.0 {
style.letter_spacing * (base / font_size)
} else {
style.letter_spacing
};
let mut width = base + tracking + style.extra_char_spacing + style.extra_word_spacing;
if style.letter_spacing + style.extra_char_spacing < 0.0 {
width = width.max(base * 0.5);
}
width
}
pub(crate) fn no_ls_short_label_cell(
cell: &crate::model::table::Cell,
table: &crate::model::table::Table,
cell_inner_width: f64,
cell_inner_height: f64,
styles: &ResolvedStyleSet,
dpi: f64,
) -> bool {
if cell.paragraphs.is_empty() || cell_inner_width <= 0.0 || cell_inner_height <= 0.0 {
return false;
}
let bf_has_diagonal = |bf_id: u16| {
bf_id != 0
&& styles
.border_styles
.get((bf_id as usize).saturating_sub(1))
.is_some_and(crate::renderer::layout::border_style_has_diagonal)
};
let cell_has_diagonal = bf_has_diagonal(cell.border_fill_id)
|| table.zones.iter().any(|z| {
z.start_row <= cell.row
&& cell.row <= z.end_row
&& z.start_col <= cell.col
&& cell.col <= z.end_col
&& bf_has_diagonal(z.border_fill_id)
});
let fixed_ls_contradicts_declared = {
let mut sum = 0.0f64;
let all_fixed = cell.paragraphs.iter().all(|p| {
styles
.para_styles
.get(p.para_shape_id as usize)
.map(|ps| {
if ps.line_spacing_type == crate::model::style::LineSpacingType::Fixed {
sum += ps.line_spacing;
true
} else {
false
}
})
.unwrap_or(false)
});
all_fixed && sum > cell_inner_height
};
if !cell_has_diagonal && !fixed_ls_contradicts_declared {
return false;
}
if !cell.paragraphs.iter().all(|p| p.line_segs.is_empty()) {
return false;
}
let mut em_sum = 0.0f64;
for p in &cell.paragraphs {
let mut comp = compose_paragraph_in_context(p, styles);
recompose_cell_lines_in_frame(
&mut comp,
p,
ParagraphBox::content_for_style(
cell_inner_width,
styles.para_styles.get(p.para_shape_id as usize),
dpi,
),
styles,
dpi,
false,
);
if comp.lines.len() > 1 {
return false;
}
if let Some(l) = comp.lines.first() {
if estimate_composed_line_width(l, styles) > cell_inner_width * 0.85 {
return false;
}
em_sum += l
.runs
.iter()
.map(|r| {
styles
.char_styles
.get(r.char_style_id as usize)
.map(|cs| cs.font_size)
.unwrap_or(0.0)
})
.fold(0.0f64, f64::max);
}
}
cell_inner_height >= em_sum
}
pub fn recompose_stored_single_line_if_overflowing(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
) {
recompose_stored_single_line_if_overflowing_cached(
composed,
para,
cell_inner_width_px,
styles,
dpi,
None,
);
}
fn recompose_stored_single_line_if_overflowing_cached(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
cache: Option<&SingleLineOverflowCache>,
) {
match recompose_stored_single_line_if_overflowing_cached_with_storage(
composed,
para,
cell_inner_width_px,
styles,
dpi,
cache,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn recompose_stored_single_line_if_overflowing_cached_with_storage<
S: crate::storage::Storage,
>(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
cache: Option<&SingleLineOverflowCache>,
storage: &S,
) -> Result<(), S::Error> {
{
if composed.lines.len() != 1 || cell_inner_width_px <= 0.0 {
return Ok(());
}
let authentic_stored = !para.line_segs.is_empty()
&& para
.line_segs
.iter()
.all(|seg| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
if authentic_stored && para.line_segs.len() >= 2 {
let note_bullet = matches!(para.text.trim_start().chars().next(), Some('※' | '☞'));
let short_note_cell = note_bullet
&& (2..=3).contains(¶.line_segs.len())
&& para.line_segs.iter().all(|seg| {
seg.segment_width > 0
&& (crate::renderer::hwpunit_to_px(seg.segment_width, dpi)
- cell_inner_width_px)
.abs()
<= 1.0
});
if !short_note_cell {
return Ok(());
}
let mut over = false;
for line in &composed.lines {
if estimate_composed_line_width_with_storage(line, styles, storage)?
> cell_inner_width_px * 1.10
{
over = true;
break;
}
}
if over {
reflow_cell_line_ignoring_stored_segs_with_storage(
composed,
para,
cell_inner_width_px,
styles,
dpi,
storage,
)?;
}
return Ok(());
}
let stored_single = para.line_segs.len() == 1 && authentic_stored;
if !stored_single {
return Ok(());
}
let width_key = (cell_inner_width_px as f32).to_bits();
if let Some(cache) = cache {
cache.use_section_tab_key(styles.section_tab_key());
}
let over = if let Some(value) = cache.and_then(|cache| cache.get(para, width_key)) {
value
} else {
let measured = if let Some(line) = composed.lines.first() {
estimate_composed_line_width_with_storage(line, styles, storage)?
> cell_inner_width_px * 1.8
} else {
false
};
if let Some(cache) = cache {
cache.insert_with_storage(para, width_key, measured, storage)?;
}
measured
};
if !over {
return Ok(());
}
if if let Some(line) = composed.lines.first() {
line_overflow_is_leader_fill_with_storage(line, styles, cell_inner_width_px, storage)?
} else {
false
} {
return Ok(());
}
reflow_cell_line_ignoring_stored_segs_with_storage(
composed,
para,
cell_inner_width_px,
styles,
dpi,
storage,
)?;
};
Ok(())
}
fn is_leader_char(c: char) -> bool {
matches!(
c,
'.' | '\u{00B7}' | '\u{2024}' | '\u{2025}' | '\u{2026}' | '\u{2027}' | '\u{22EF}'
)
}
const MIN_LEADER_RUN: usize = 4;
fn leader_fill_spans(chars: &[char]) -> Vec<std::ops::Range<usize>> {
match leader_fill_spans_with_storage(chars, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn leader_fill_spans_with_storage<S: crate::storage::Storage>(
chars: &[char],
storage: &S,
) -> Result<Vec<std::ops::Range<usize>>, S::Error> {
Ok({
let mut spans = Vec::new();
let mut start = 0;
while start < chars.len() {
if !is_leader_char(chars[start]) {
start += 1;
continue;
}
let mut end = start + 1;
while end < chars.len() && is_leader_char(chars[end]) {
end += 1;
}
if end - start >= MIN_LEADER_RUN {
storage.push(&mut spans, start..end)?;
}
start = end;
}
spans
})
}
fn trim_leader_fill_overflow(
composed: &mut ComposedParagraph,
inner_width_px: f64,
styles: &ResolvedStyleSet,
) {
match trim_leader_fill_overflow_with_storage(
composed,
inner_width_px,
styles,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn trim_leader_fill_overflow_with_storage<S: crate::storage::Storage>(
composed: &mut ComposedParagraph,
inner_width_px: f64,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<(), S::Error> {
let _: () = {
if inner_width_px <= 0.0 {
return Ok(());
}
for line in &mut composed.lines {
let mut width = estimate_composed_line_width_with_storage(line, styles, storage)?;
if width <= inner_width_px
|| !line_overflow_is_leader_fill_with_storage(
line,
styles,
inner_width_px,
storage,
)?
{
continue;
}
for run_idx in (0..line.runs.len()).rev() {
if width <= inner_width_px {
break;
}
let style = line.runs[run_idx].try_text_style(styles, storage)?;
let run = &mut line.runs[run_idx];
let mut chars: Vec<char> =
storage.collect(effective_text_for_metrics(run).chars())?;
for span in leader_fill_spans_with_storage(&chars, storage)?
.into_iter()
.rev()
{
if width <= inner_width_px {
break;
}
let current: String = storage.chars(chars.iter().copied())?;
let current_width = estimate_text_width(¤t, &style);
let without = |drop: usize| -> Result<String, S::Error> {
storage.chars(
chars[..span.end - drop]
.iter()
.chain(&chars[span.end..])
.copied(),
)
};
let mut low = 0;
let mut high = span.len();
while low < high {
let middle = (low + high) / 2;
let candidate_width = estimate_text_width(&without(middle)?, &style);
if width - current_width + candidate_width <= inner_width_px {
high = middle;
} else {
low = middle + 1;
}
}
let kept = without(low)?;
width += estimate_text_width(&kept, &style) - current_width;
chars.drain(span.end - low..span.end);
run.display_text = Some(kept);
}
}
}
};
Ok(())
}
pub(crate) fn line_overflow_is_leader_fill(
line: &ComposedLine,
styles: &ResolvedStyleSet,
inner_width_px: f64,
) -> bool {
match line_overflow_is_leader_fill_with_storage(
line,
styles,
inner_width_px,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn line_overflow_is_leader_fill_with_storage<S: crate::storage::Storage>(
line: &ComposedLine,
styles: &ResolvedStyleSet,
inner_width_px: f64,
storage: &S,
) -> Result<bool, S::Error> {
Ok({
fn strip_leader_runs<S: crate::storage::Storage>(
text: &str,
storage: &S,
) -> Result<(String, bool), S::Error> {
let mut chars = storage.collect(text.chars())?;
let spans = leader_fill_spans_with_storage(&chars, storage)?;
let found = !spans.is_empty();
for span in spans.into_iter().rev() {
chars.drain(span);
}
Ok((storage.chars(chars.iter().copied())?, found))
}
let mut found_leader = false;
let mut content_width = 0.0f64;
for run in &line.runs {
let (kept, found) = strip_leader_runs(effective_text_for_metrics(run), storage)?;
found_leader |= found;
if !kept.is_empty() {
content_width += estimate_text_width(&kept, &run.try_text_style(styles, storage)?);
}
}
found_leader && content_width <= inner_width_px
})
}
fn reflow_cell_line_ignoring_stored_segs(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
) {
match reflow_cell_line_ignoring_stored_segs_with_storage(
composed,
para,
cell_inner_width_px,
styles,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn reflow_cell_line_ignoring_stored_segs_with_storage<S: crate::storage::Storage>(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<(), S::Error> {
{
let mut para_no_ls = storage.clone_paragraph(para)?;
para_no_ls.line_segs.clear();
recompose_cell_lines_in_frame_with_storage(
composed,
¶_no_ls,
ParagraphBox::content_for_style(
cell_inner_width_px,
styles.para_styles.get(para.para_shape_id as usize),
dpi,
),
styles,
dpi,
false,
storage,
)?;
};
Ok(())
}
pub(crate) fn recompose_horizontal_cell_lines_for_width(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
stored_geometry_policy: impl Into<crate::model::provenance::StoredGeometryPolicy>,
repair_stored_overflow: bool,
overflow_cache: &SingleLineOverflowCache,
line_wrap_squeeze: bool,
) {
match recompose_horizontal_cell_lines_for_width_with_storage(
composed,
para,
cell_inner_width_px,
styles,
dpi,
stored_geometry_policy,
repair_stored_overflow,
overflow_cache,
line_wrap_squeeze,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn recompose_horizontal_cell_lines_for_width_with_storage<S: crate::storage::Storage>(
composed: &mut ComposedParagraph,
para: &Paragraph,
cell_inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
stored_geometry_policy: impl Into<crate::model::provenance::StoredGeometryPolicy>,
repair_stored_overflow: bool,
overflow_cache: &SingleLineOverflowCache,
line_wrap_squeeze: bool,
storage: &S,
) -> Result<(), S::Error> {
let _: () = {
recompose_cell_lines_in_frame_with_storage(
composed,
para,
ParagraphBox::content_for_style(
cell_inner_width_px,
styles.para_styles.get(para.para_shape_id as usize),
dpi,
)
.with_line_wrap_squeeze(line_wrap_squeeze),
styles,
dpi,
stored_geometry_policy,
storage,
)?;
if repair_stored_overflow && !line_wrap_squeeze {
recompose_stored_single_line_if_overflowing_cached_with_storage(
composed,
para,
cell_inner_width_px,
styles,
dpi,
Some(overflow_cache),
storage,
)?;
}
};
Ok(())
}
pub(crate) fn stored_rows_are_stale(
composed: &ComposedParagraph,
para: &Paragraph,
inner_width_px: f64,
styles: &ResolvedStyleSet,
line_wrap_squeeze: bool,
) -> bool {
match stored_rows_are_stale_with_storage(
composed,
para,
inner_width_px,
styles,
line_wrap_squeeze,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn stored_rows_are_stale_with_storage<S: crate::storage::Storage>(
composed: &ComposedParagraph,
para: &Paragraph,
inner_width_px: f64,
styles: &ResolvedStyleSet,
line_wrap_squeeze: bool,
storage: &S,
) -> Result<bool, S::Error> {
Ok({
if !para.line_segs.is_empty() && para.stored_text_partition_is_dirty() {
return Ok(true);
}
if !para.line_segs.is_empty() && para.stored_rows_include_hidden_guide() {
return Ok(true);
}
let stored = !para.line_segs.is_empty()
&& para
.line_segs
.iter()
.all(|seg| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
if !stored
|| composed.lines.is_empty()
|| inner_width_px <= 0.0
|| composed.lines.len() != para.line_segs.len()
{
return Ok(false);
}
for l in composed.lines.iter().filter(|_| !line_wrap_squeeze) {
if estimate_composed_line_width_with_storage(l, styles, storage)? > inner_width_px * 1.8
&& !line_overflow_is_leader_fill_with_storage(l, styles, inner_width_px, storage)?
{
return Ok(true);
}
}
if stored_rows_underfill_inside_token_with_storage(
composed,
para,
inner_width_px,
styles,
storage,
)? {
return Ok(true);
}
if !para.controls.iter().any(|c| {
matches!(c, crate::model::control::Control::Table(t)
if !t.common.treat_as_char
&& matches!(t.common.text_wrap, crate::model::shape::TextWrap::TopAndBottom))
}) {
return Ok(false);
}
let non_last_overfull = |line: &ComposedLine, seg: &crate::model::paragraph::LineSeg| {
let est = estimate_composed_line_width(line, styles);
let seg_width_px = crate::renderer::hwpunit_to_px(seg.segment_width, 96.0);
est > inner_width_px * 1.06 + 12.0 && est > seg_width_px * 1.06 + 12.0
};
composed
.lines
.iter()
.zip(para.line_segs.iter())
.take(composed.lines.len().saturating_sub(1))
.any(|(line, seg)| non_last_overfull(line, seg))
})
}
fn stored_last_row_is_rejoinable_word_tail(
composed: &ComposedParagraph,
para: &Paragraph,
styles: &ResolvedStyleSet,
) -> bool {
match stored_last_row_is_rejoinable_word_tail_with_storage(
composed,
para,
styles,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn stored_last_row_is_rejoinable_word_tail_with_storage<S: crate::storage::Storage>(
composed: &ComposedParagraph,
para: &Paragraph,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<bool, S::Error> {
Ok({
use crate::model::style::Alignment;
let n = composed.lines.len();
if n < 2 || n != para.line_segs.len() {
return Ok(false);
}
let Some(para_style) = styles.para_styles.get(para.para_shape_id as usize) else {
return Ok(false);
};
let recomposed_by_hancom = para_style.condense_min_space != 0
|| para_style.head_type != crate::model::style::HeadType::None;
if para_style.alignment != Alignment::Justify || !recomposed_by_hancom {
return Ok(false);
}
let (prev, last) = (&composed.lines[n - 2], &composed.lines[n - 1]);
if prev.has_line_break {
return Ok(false);
}
let is_syllable = |c: char| ('\u{ac00}'..='\u{d7a3}').contains(&c);
let prev_text: String = storage.chars(prev.runs.iter().flat_map(|run| run.text.chars()))?;
let tail_text: String = storage.chars(last.runs.iter().flat_map(|run| run.text.chars()))?;
let tail = tail_text.trim_end();
!tail.is_empty()
&& !tail.chars().any(char::is_whitespace)
&& prev_text.chars().last().is_some_and(is_syllable)
&& tail.chars().next().is_some_and(is_syllable)
})
}
fn stored_rows_underfill_inside_token(
composed: &ComposedParagraph,
para: &Paragraph,
inner_width_px: f64,
styles: &ResolvedStyleSet,
) -> bool {
match stored_rows_underfill_inside_token_with_storage(
composed,
para,
inner_width_px,
styles,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn stored_rows_underfill_inside_token_with_storage<S: crate::storage::Storage>(
composed: &ComposedParagraph,
para: &Paragraph,
inner_width_px: f64,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<bool, S::Error> {
Ok({
use crate::model::style::Alignment;
const MIN_SPARE_CHARS: f64 = 2.0;
if composed.lines.len() < 2 {
return Ok(false);
}
let Some(para_style) = styles.para_styles.get(para.para_shape_id as usize) else {
return Ok(false);
};
if matches!(
para_style.alignment,
Alignment::Justify | Alignment::Distribute | Alignment::Split
) {
return Ok(false);
}
let is_syllable = |c: char| ('\u{ac00}'..='\u{d7a3}').contains(&c);
let line_text =
|line: &ComposedLine| storage.chars(line.runs.iter().flat_map(|run| run.text.chars()));
let has_opaque_inline = |start: usize, end: usize| {
composed
.tac_controls
.iter()
.any(|&(pos, _, _)| (start..end).contains(&pos))
|| composed
.footnote_positions
.iter()
.any(|&(pos, _, _)| (start..end).contains(&pos))
};
let first_line_indent = para_style.indent.max(0.0);
let hanging_indent = (-para_style.indent).max(0.0);
for (idx, (pair, seg)) in composed
.lines
.windows(2)
.zip(para.line_segs.iter())
.enumerate()
{
let (line, next) = (&pair[0], &pair[1]);
if line.has_line_break {
continue;
}
let text = line_text(line)?;
let next_text = line_text(next)?;
let nchars = text.chars().count();
if nchars == 0
|| text.chars().any(|c| c.is_whitespace())
|| !text.chars().last().is_some_and(is_syllable)
|| !next_text.chars().next().is_some_and(is_syllable)
|| has_opaque_inline(line.char_start, next.char_start)
{
continue;
}
let used = estimate_composed_line_width_with_storage(line, styles, storage)?;
if used <= 0.0 {
continue;
}
let indent = if idx == 0 {
first_line_indent
} else {
hanging_indent
};
let seg_width_px = hwpunit_to_px(seg.segment_width, 96.0);
if seg_width_px > inner_width_px + 1.0 {
continue;
}
let declared = seg_width_px - indent;
let avg_char = used / nchars as f64;
if declared - used >= avg_char * MIN_SPARE_CHARS {
return Ok(true);
}
}
false
})
}
pub(crate) fn recompose_stored_lines_in_frame(
composed: &ComposedParagraph,
para: &Paragraph,
paragraph_box: ParagraphBox,
inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
stored_geometry_policy: impl Into<crate::model::provenance::StoredGeometryPolicy>,
miss_policy: line_breaking::StoredRowMissPolicy,
float_carve_evidence: &[crate::renderer::float_placement::FloatCarveEvidence],
) -> Option<ComposedParagraph> {
match recompose_stored_lines_in_frame_with_storage(
composed,
para,
paragraph_box,
inner_width_px,
styles,
dpi,
stored_geometry_policy,
miss_policy,
float_carve_evidence,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn recompose_stored_lines_in_frame_with_storage<S: crate::storage::Storage>(
composed: &ComposedParagraph,
para: &Paragraph,
paragraph_box: ParagraphBox,
inner_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
stored_geometry_policy: impl Into<crate::model::provenance::StoredGeometryPolicy>,
miss_policy: line_breaking::StoredRowMissPolicy,
float_carve_evidence: &[crate::renderer::float_placement::FloatCarveEvidence],
storage: &S,
) -> Result<Option<ComposedParagraph>, S::Error> {
Ok({
recompose_stored_lines_in_frame_with_known_square_band_with_storage(
composed,
para,
paragraph_box,
inner_width_px,
styles,
dpi,
stored_geometry_policy,
miss_policy,
float_carve_evidence,
false,
false,
false,
&[],
storage,
)?
})
}