#[derive(Debug, Clone, Copy)]
pub(crate) struct StoredTacLine {
pub control: usize,
pub top: i32,
pub end: i32,
pub occupied_end: i32,
}
pub(crate) fn stored_first_tac_line(para: &Paragraph) -> Option<&LineSeg> {
let first = para.line_segs.first()?;
if para.stored_text_partition_dirty
|| para
.line_segs
.iter()
.any(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0)
|| para
.text
.chars()
.any(|c| !c.is_whitespace() && c > '\u{001f}' && c != '\u{fffc}')
{
return None;
}
para.controls
.iter()
.enumerate()
.any(|(ci, control)| {
let Control::Table(table) = control else {
return false;
};
table.common.treat_as_char
&& table.caption.is_none()
&& control_line_seg_index(para, ci) == Some(0)
&& i64::from(first.line_height)
== i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom)
})
.then_some(first)
}
pub(crate) fn stored_owned_tac_line(
para: &Paragraph,
control_index: usize,
) -> Option<(usize, &LineSeg)> {
if para.stored_text_partition_dirty
|| para
.line_segs
.iter()
.any(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0)
|| para
.text
.chars()
.any(|c| !c.is_whitespace() && c > '\u{001f}' && c != '\u{fffc}')
{
return None;
}
let Control::Table(table) = para.controls.get(control_index)? else {
return None;
};
if !table.common.treat_as_char || table.caption.is_some() {
return None;
}
let owner = control_line_seg_index(para, control_index)?;
let line = para.line_segs.get(owner)?;
let shares_line = para.controls.iter().enumerate().any(|(index, control)| {
index != control_index
&& match control {
Control::Table(other) => other.common.treat_as_char,
Control::Picture(picture) => picture.common.treat_as_char,
Control::Shape(shape) => shape.common().treat_as_char,
_ => false,
}
&& control_line_seg_index(para, index) == Some(owner)
});
(!shares_line
&& i64::from(line.line_height)
== i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom))
.then_some((owner, line))
}
pub(crate) fn ordinary_tac_prefix_rows(para: &Paragraph, owner: usize) -> bool {
!para.text.is_empty()
&& para.text.chars().all(char::is_whitespace)
&& stored_prefix_rows_are_text_rows(para, owner)
}
pub(crate) fn owned_tac_prefix_rows(para: &Paragraph, owner: usize) -> bool {
ordinary_tac_prefix_rows(para, owner)
|| (para.text.is_empty()
&& !crate::renderer::para_has_no_stored_line_segs(para)
&& para
.controls
.iter()
.take_while(|control| !control.is_treat_as_char_object())
.any(|control| matches!(control, Control::Field(_)))
&& stored_prefix_rows_are_text_rows(para, owner))
}
fn stored_prefix_rows_are_text_rows(para: &Paragraph, owner: usize) -> bool {
owner > 0
&& para.line_segs.get(owner).is_some_and(|row| {
row.vertical_pos >= para.line_segs[0].vertical_pos
&& para.line_segs[..=owner]
.windows(2)
.all(|pair| pair[1].vertical_pos >= pair[0].vertical_pos)
&& para.line_segs[..owner]
.iter()
.all(|prefix| prefix.line_height == prefix.text_height)
})
}
pub(crate) fn stored_tac_lines(para: &Paragraph) -> Option<Vec<StoredTacLine>> {
let whitespace_carrier = !para.text.is_empty() && para.text.chars().all(char::is_whitespace);
if !whitespace_carrier {
para.empty_control_stream_position(0)?;
}
if para.stored_text_partition_dirty
|| para
.line_segs
.iter()
.any(|s| s.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0)
{
return None;
}
let origin = para.line_segs.first()?.vertical_pos;
let mut lines = Vec::new();
let mut previous_owner = None;
for (ci, control) in para.controls.iter().enumerate() {
let table = match control {
Control::Table(table) if table.common.treat_as_char => table,
Control::SectionDef(_)
| Control::ColumnDef(_)
| Control::Header(_)
| Control::Footer(_)
| Control::PageNumberPos(_)
| Control::PageHide(_)
| Control::Field(_) => continue,
_ => return None,
};
let owner = control_line_seg_index(para, ci)?;
let seg = para.line_segs.get(owner)?;
let caption_extent = match &table.caption {
None => 0,
Some(caption) => {
if caption.direction != crate::model::shape::CaptionDirection::Bottom
|| caption.paragraphs.is_empty()
|| caption.paragraphs.iter().any(|paragraph| {
paragraph.stored_text_partition_is_dirty()
|| paragraph.cell_format_vpos_dirty
|| paragraph.line_segs.is_empty()
|| paragraph.line_segs.iter().any(|line| {
line.line_height <= 0
|| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
})
})
{
return None;
}
i64::from(crate::renderer::px_to_hwpunit(
caption_height_px(&table.caption, crate::renderer::DEFAULT_DPI),
crate::renderer::DEFAULT_DPI,
)) + i64::from(caption.spacing)
}
};
let outer_height = i64::from(table.common.height)
+ i64::from(table.outer_margin_top)
+ i64::from(table.outer_margin_bottom)
+ caption_extent;
if previous_owner.is_some_and(|previous| previous >= owner)
|| i64::from(seg.line_height) != outer_height
|| seg.vertical_pos < origin
{
return None;
}
if ordinary_tac_prefix_rows(para, owner) {
return None;
}
if (whitespace_carrier || (lines.is_empty() && owner > 0))
&& (table.caption.is_some()
|| owner == 0
|| para.line_segs[..owner].iter().any(|blank| {
blank.text_height <= 0
|| i64::from(blank.text_height) + i64::from(blank.line_spacing) < 0
})
|| i64::from(seg.text_height) != outer_height
|| para.line_segs[..owner].windows(2).any(|pair| {
i64::from(pair[0].vertical_pos)
+ i64::from(pair[0].text_height)
+ i64::from(pair[0].line_spacing)
!= i64::from(pair[1].vertical_pos)
})
|| i64::from(para.line_segs[owner - 1].vertical_pos)
+ i64::from(para.line_segs[owner - 1].text_height)
+ i64::from(para.line_segs[owner - 1].line_spacing)
!= i64::from(seg.vertical_pos))
{
return None;
}
let top = seg.vertical_pos.checked_sub(origin)?;
if lines
.last()
.is_some_and(|line: &StoredTacLine| line.top >= top)
{
return None;
}
let occupied_end = top.checked_add(seg.line_height)?;
let end = occupied_end.checked_add(seg.line_spacing)?;
if end < top {
return None;
}
lines.push(StoredTacLine {
control: ci,
top,
occupied_end,
end,
});
previous_owner = Some(owner);
}
let single_prefix_carrier = lines.len() == 1
&& previous_owner.is_some_and(|owner| owner > 0 && owner == para.line_segs.len() - 1);
if lines.len() < 2 && !whitespace_carrier && !single_prefix_carrier {
return None;
}
if whitespace_carrier && (lines.len() != 1 || previous_owner != Some(para.line_segs.len() - 1))
{
return None;
}
for i in 0..lines.len() - 1 {
lines[i].end = lines[i + 1].top;
}
Some(lines)
}
pub fn caption_height_px(caption: &Option<Caption>, dpi: f64) -> f64 {
caption_height_px_in_context(caption, None, dpi)
}
pub(crate) fn caption_height_px_in_context(
caption: &Option<Caption>,
styles: Option<&ResolvedStyleSet>,
dpi: f64,
) -> f64 {
match caption_height_px_in_context_with_storage(
caption,
styles,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn caption_height_px_in_context_with_storage<S: crate::storage::Storage>(
caption: &Option<Caption>,
styles: Option<&ResolvedStyleSet>,
dpi: f64,
storage: &S,
) -> Result<f64, S::Error> {
let caption = match caption {
Some(c) => c,
None => return Ok(0.0),
};
if caption.paragraphs.is_empty() {
return Ok(0.0);
}
const DEFAULT_LINE_HEIGHT_HWPUNIT: i32 = 400;
let mut line_seg_height = 0.0f64;
let mut composed_height = 0.0f64;
for para in &caption.paragraphs {
if let (Some(first), Some(last)) = (para.line_segs.first(), para.line_segs.last()) {
let para_top = first.vertical_pos.min(0);
let para_bottom = last.vertical_pos.saturating_add(last.line_height);
line_seg_height = line_seg_height.max(hwpunit_to_px(para_bottom - para_top, dpi));
}
let composed = compose_caption_paragraph_with_storage(para, styles, storage)?;
if composed.lines.is_empty() {
let own_font_size = styles
.filter(|_| para.line_segs.is_empty())
.and_then(|styles| {
let id = para
.char_shape_id_at(0)
.or_else(|| para.char_shapes.first().map(|shape| shape.char_shape_id))?;
styles.char_styles.get(id as usize)
})
.map(|style| style.font_size)
.filter(|size| *size > 0.0);
composed_height +=
own_font_size.unwrap_or_else(|| hwpunit_to_px(DEFAULT_LINE_HEIGHT_HWPUNIT, dpi));
} else {
for (i, line) in composed.lines.iter().enumerate() {
let line_h = hwpunit_to_px(line.line_height, dpi);
let spacing = if i < composed.lines.len() - 1 {
hwpunit_to_px(line.line_spacing, dpi)
} else {
0.0 };
composed_height += line_h + spacing;
}
}
}
Ok(line_seg_height.max(composed_height))
}
pub(crate) fn inline_shape_width_hu(shape: &ShapeObject) -> i32 {
let width = shape.common().width as i32;
match shape_caption_for_layout(shape) {
Some(caption)
if matches!(
caption.direction,
CaptionDirection::Left | CaptionDirection::Right
) =>
{
width
.saturating_add(caption.width as i32)
.saturating_add(i32::from(caption.spacing))
}
_ => width,
}
}
pub(crate) fn shape_caption_for_layout(shape: &ShapeObject) -> Option<Caption> {
match shape {
ShapeObject::Line(s) => s.drawing.caption.clone(),
ShapeObject::Rectangle(s) => s.drawing.caption.clone(),
ShapeObject::Ellipse(s) => s.drawing.caption.clone(),
ShapeObject::Arc(s) => s.drawing.caption.clone(),
ShapeObject::Polygon(s) => s.drawing.caption.clone(),
ShapeObject::Curve(s) => s.drawing.caption.clone(),
ShapeObject::Group(s) => s.caption.clone(),
ShapeObject::Picture(s) => s.caption.clone(),
ShapeObject::Chart(s) => s.caption.clone().or_else(|| s.drawing.caption.clone()),
ShapeObject::Ole(s) => s.caption.clone().or_else(|| s.drawing.caption.clone()),
}
}
pub(crate) fn captioned_shape_height_px(
shape_height: f64,
caption: &Option<Caption>,
dpi: f64,
) -> f64 {
let Some(cap) = caption.as_ref().filter(|cap| !cap.paragraphs.is_empty()) else {
return shape_height;
};
let caption_height = caption_height_px(caption, dpi);
match cap.direction {
CaptionDirection::Top | CaptionDirection::Bottom => {
shape_height + hwpunit_to_px(cap.spacing as i32, dpi) + caption_height
}
CaptionDirection::Left | CaptionDirection::Right => shape_height.max(caption_height),
}
}
fn try_convert_pua_display_text<S: crate::storage::Storage>(
composed: &mut ComposedParagraph,
soft_hyphen_control: bool,
styles: Option<&ResolvedStyleSet>,
storage: &S,
) -> Result<(), S::Error> {
use super::pua_oldhangul::map_pua_old_hangul;
let product_prefix_starts = try_legacy_hancom_product_prefix_starts(composed, storage)?;
let mut run_char_start = 0usize;
for line in composed.lines.iter_mut() {
let line_last_run = line.runs.iter().rposition(|run| !run.text.is_empty());
for (run_index, run) in line.runs.iter_mut().enumerate() {
let program = match styles {
Some(styles) => run.try_text_style(styles, storage)?.native_pua_metrics,
None => None,
};
let chars: Vec<char> = storage.collect(run.text.chars())?;
run.literal_soft_hyphen = !soft_hyphen_control && chars.contains(&'\u{00AD}');
let run_char_end = run_char_start + chars.len();
let has_product_projection = product_prefix_starts
.iter()
.any(|start| *start < run_char_end && start.saturating_add(3) > run_char_start);
let has_pua_display = chars.iter().any(|ch| {
pua_plain_text_display(*ch).is_some()
|| map_pua_old_hangul(*ch).is_some()
|| map_pua_bullet_char(*ch) != *ch
|| *ch == '\u{00AD}'
});
let line_end_char = if Some(run_index) == line_last_run {
chars.len().checked_sub(1)
} else {
None
};
if !has_product_projection && !has_pua_display {
run_char_start = run_char_end;
continue;
}
let mut display = storage.string("")?;
let mut changed = false;
for (index, ch) in chars.iter().copied().enumerate() {
let char_position = run_char_start + index;
if product_prefix_starts.contains(&char_position) {
storage.push_char(&mut display, '한')?;
changed = true;
} else if product_prefix_starts
.iter()
.any(|start| (start + 1..start + 3).contains(&char_position))
{
changed = true;
} else if ch == '\u{00AD}' {
if !soft_hyphen_control || line_end_char == Some(index) {
storage.push_char(&mut display, '-')?;
}
changed = true;
} else if program
.as_ref()
.is_some_and(|program| program.advance_em(ch).is_some())
|| super::enclosed_pua(hancom_symbol_display_key(ch)).is_some()
{
let source = hancom_symbol_display_key(ch);
storage.push_char(&mut display, source)?;
changed |= source != ch;
} else if let Some(replacement) = pua_plain_text_display(ch) {
storage.push_str(&mut display, replacement)?;
changed = true;
} else if let Some(jamos) = map_pua_old_hangul(ch) {
for &jamo in jamos {
storage.push_char(&mut display, jamo)?;
}
changed = true;
} else {
let mapped = map_pua_bullet_char(ch);
storage.push_char(&mut display, mapped)?;
if mapped != ch {
changed = true;
}
}
}
run_char_start = run_char_end;
run.display_text = changed.then_some(display);
}
}
Ok(())
}
const LEGACY_HANCOM_PRODUCT_WORDS: [(&str, &str); 4] = [
("ᄒᆞᆫ글", "한글"),
("ᄒᆞᆫ메일", "한메일"),
("ᄒᆞᆫ팩스", "한팩스"),
("ᄒᆞᆫ소프트", "한소프트"),
];
pub(crate) fn legacy_hancom_product_display_text(text: &str) -> Option<String> {
let mut display = text.to_owned();
for (legacy, modern) in LEGACY_HANCOM_PRODUCT_WORDS {
display = display.replace(legacy, modern);
}
(display != text).then_some(display)
}
fn try_legacy_hancom_product_prefix_starts<S: crate::storage::Storage>(
composed: &ComposedParagraph,
storage: &S,
) -> Result<Vec<usize>, S::Error> {
let mut logical_text = storage.string("")?;
for text in composed
.lines
.iter()
.flat_map(|line| line.runs.iter())
.map(|run| run.text.as_str())
{
storage.push_str(&mut logical_text, text)?;
}
let mut starts = storage.vec(0)?;
for (char_index, (byte_index, _)) in logical_text.char_indices().enumerate() {
if LEGACY_HANCOM_PRODUCT_WORDS
.iter()
.any(|(legacy, _)| logical_text[byte_index..].starts_with(legacy))
{
storage.push(&mut starts, char_index)?;
}
}
Ok(starts)
}
fn inject_footnote_markers(lines: &mut [ComposedLine], positions: &[(usize, u16)]) {
for &(char_pos, number) in positions {
let marker_text = format!("{})", number);
for line in lines.iter_mut() {
let line_start = line.char_start;
let line_end = line_start
+ line
.runs
.iter()
.map(|r| r.text.chars().count())
.sum::<usize>();
if char_pos < line_start || char_pos > line_end {
continue;
}
let mut run_char = line_start;
let mut target_run_idx = None;
let mut offset_in_run = 0;
for (ri, run) in line.runs.iter().enumerate() {
let run_len = run.text.chars().count();
if char_pos >= run_char && char_pos <= run_char + run_len {
target_run_idx = Some(ri);
offset_in_run = char_pos - run_char;
break;
}
run_char += run_len;
}
if let Some(ri) = target_run_idx {
let orig_run = &line.runs[ri];
let cs_id = orig_run.char_style_id;
let lang = orig_run.lang_index;
let orig_text: Vec<char> = orig_run.text.chars().collect();
let before: String = orig_text[..offset_in_run].iter().collect();
let after: String = orig_text[offset_in_run..].iter().collect();
let marker_run = ComposedTextRun {
text: marker_text.clone(),
char_style_id: cs_id,
lang_index: lang,
neutral_space_origin: None,
char_overlap: None,
footnote_marker: Some(number),
display_text: None,
supplemental_metrics_blocked: false,
inserted_control_text: false,
space_metric: crate::renderer::composer::SpaceMetric::Stored,
regenerated_font_metrics: line.runs[ri].regenerated_font_metrics,
literal_figure_space: line.runs[ri].literal_figure_space,
literal_soft_hyphen: line.runs[ri].literal_soft_hyphen,
};
let mut new_runs = Vec::new();
for (i, run) in line.runs.iter().enumerate() {
if i == ri {
if !before.is_empty() {
new_runs.push(ComposedTextRun {
text: before.clone(),
char_style_id: cs_id,
lang_index: lang,
neutral_space_origin: None,
char_overlap: run.char_overlap.clone(),
footnote_marker: None,
display_text: None,
supplemental_metrics_blocked: run.supplemental_metrics_blocked,
inserted_control_text: run.inserted_control_text,
space_metric: run.space_metric,
regenerated_font_metrics: run.regenerated_font_metrics,
literal_figure_space: run.literal_figure_space,
literal_soft_hyphen: run.literal_soft_hyphen,
});
}
new_runs.push(marker_run.clone());
if !after.is_empty() {
new_runs.push(ComposedTextRun {
text: after.clone(),
char_style_id: cs_id,
lang_index: lang,
neutral_space_origin: None,
char_overlap: run.char_overlap.clone(),
footnote_marker: None,
display_text: None,
supplemental_metrics_blocked: run.supplemental_metrics_blocked,
inserted_control_text: run.inserted_control_text,
space_metric: run.space_metric,
regenerated_font_metrics: run.regenerated_font_metrics,
literal_figure_space: run.literal_figure_space,
literal_soft_hyphen: run.literal_soft_hyphen,
});
}
} else {
new_runs.push(run.clone());
}
}
line.runs = new_runs;
break; }
}
}
}
fn stored_line_box_height(seg: &LineSeg) -> i32 {
seg.line_height.max(seg.text_height)
}
pub(crate) fn captioned_picture_height_px(picture: &crate::model::image::Picture, dpi: f64) -> f64 {
let (_, height) = super::layout::picture_flow_frame_size_hu(picture);
captioned_shape_height_px(hwpunit_to_px(height, dpi), &picture.caption, dpi)
}