use super::super::composer::{compose_paragraph, ComposedLine, ComposedParagraph};
use super::super::page_layout::LayoutRect;
use super::super::pagination::{FootnoteFragment, FootnoteRef, FootnoteSource};
use super::super::render_tree::*;
use super::super::style_resolver::ResolvedStyleSet;
use super::super::{hwpunit_to_px, AutoNumberCounter, PathCommand, StrokeDash, TextStyle};
use super::border_rendering::border_width_to_px;
use super::text_measurement::{estimate_text_width, resolved_to_text_style};
use super::utils::{
extract_picture_transform, find_bin_data_bytes, picture_data_is_unusable,
picture_display_size_hu,
};
use super::{footnote_separator_length_px, LayoutEngine, ParagraphVerticalSpacing};
use crate::model::bin_data::BinDataContent;
use crate::model::control::Control;
use crate::model::footnote::{FootnoteShape, NumberFormat};
use crate::model::paragraph::Paragraph;
use crate::model::shape::{
Caption, CaptionDirection, CommonObjAttr, HorzAlign, TextWrap, VertAlign, VertRelTo,
};
pub(crate) struct BodyPicturePlacement {
pub flow_end: f64,
pub content_bottom: f64,
}
use crate::model::style::{Alignment, LineSpacingType};
#[derive(Clone, Copy, PartialEq, Eq)]
enum FootnoteParagraphRoute {
Numbered,
Plain,
StoredEmpty,
}
struct FootnoteBlockTableFrame<'a> {
table: &'a crate::model::table::Table,
measured: crate::renderer::height_measurer::MeasuredTable,
top_offset: f64,
advance: f64,
trailing_line_spacing: f64,
line_left_offset: Option<f64>,
}
struct FootnoteParagraphPlacement<'a> {
route: FootnoteParagraphRoute,
spacing: ParagraphVerticalSpacing,
block_table: Option<FootnoteBlockTableFrame<'a>>,
}
fn fragment_line_bounds(fragment: Option<FootnoteFragment>, total_lines: usize) -> (usize, usize) {
match fragment {
Some(fragment) => {
let start = fragment.start_line.min(total_lines);
let end = fragment.end_line.clamp(start, total_lines);
(start, end)
}
None => (0, total_lines),
}
}
fn fragment_draws_separator(fragment: Option<FootnoteFragment>) -> bool {
fragment
.map(|fragment| fragment.draw_separator)
.unwrap_or(true)
}
fn fragment_draws_number(fragment: Option<FootnoteFragment>) -> bool {
fragment
.map(|fragment| fragment.draw_number)
.unwrap_or(true)
}
fn compose_footnote_paragraph(
para: &Paragraph,
content_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
) -> crate::renderer::composer::ComposedParagraph {
let has_paragraph_line =
!para.text.is_empty() || (para.char_count > 0 && para.controls.is_empty());
if para.line_segs.is_empty() && has_paragraph_line && content_width_px > 0.0 {
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let margin_left = para_style.map(|s| s.margin_left).unwrap_or(0.0);
let margin_right = para_style.map(|s| s.margin_right).unwrap_or(0.0);
let final_width = (content_width_px - margin_left - margin_right).max(0.0);
if final_width > 0.0 {
let mut owned = para.clone();
crate::renderer::composer::reflow_line_segs(
&mut owned,
crate::renderer::composer::ParagraphBox::content_width_px(final_width, dpi),
styles,
dpi,
);
return crate::renderer::composer::compose_paragraph_in_context(&owned, styles);
}
}
let mut composed = crate::renderer::composer::compose_paragraph_in_context(para, styles);
if composed.lines.is_empty()
&& para.text.is_empty()
&& para.controls.is_empty()
&& !para.stored_text_partition_is_dirty()
{
if let [line] = para.line_segs.as_slice() {
if line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
&& line.line_height > 0
{
composed.lines.push(ComposedLine {
runs: Vec::new(),
line_height: line.line_height,
baseline_distance: line.baseline_distance,
segment_width: line.segment_width as i32,
column_start: line.column_start,
line_spacing: line.line_spacing,
has_line_break: false,
char_start: 0,
});
}
}
}
composed
}
fn stored_footnote_number_prefix(para: &Paragraph, number: u16) -> Option<(String, usize)> {
if para.stored_text_partition_is_dirty()
|| para.line_segs.is_empty()
|| para.line_segs.iter().any(|line| {
line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
})
{
return None;
}
let positions = para.control_text_positions();
let mut prefix = String::new();
for (index, control) in para.controls.iter().enumerate() {
let Control::AutoNumber(auto) = control else {
return None;
};
if auto.number_type != crate::model::control::AutoNumberType::Footnote
|| auto.superscript
|| !crate::renderer::note_marker::supported_format(auto.format)
|| positions.get(index) != Some(&index)
|| para.text.chars().nth(index) != Some(' ')
{
return None;
}
if auto.prefix_char != '\0' {
prefix.push(auto.prefix_char);
}
prefix.push_str(&crate::renderer::note_marker::number_text(
number,
auto.format,
auto.user_symbol,
));
if auto.suffix_char != '\0' {
prefix.push(auto.suffix_char);
}
}
Some((prefix, para.controls.len()))
}
fn footnote_composed_with_number(
para: &Paragraph,
composed: &ComposedParagraph,
number_text: &str,
selected_start: usize,
base_cs_id: u32,
) -> Option<ComposedParagraph> {
if selected_start != 0
|| composed
.lines
.first()
.is_none_or(|line| line.runs.is_empty())
{
return None;
}
let mut numbered = composed.clone();
let line = numbered.lines.first_mut()?;
let number_marker = para.controls.iter().find_map(|control| match control {
Control::AutoNumber(auto)
if auto.number_type == crate::model::control::AutoNumberType::Footnote =>
{
auto.superscript.then_some(auto.assigned_number)
}
_ => None,
});
let positions = para.control_text_positions();
let placeholder = para
.controls
.iter()
.enumerate()
.find_map(|(index, control)| match control {
Control::AutoNumber(_) => positions.get(index).copied(),
_ => None,
});
let mut run_start = line.char_start;
let mut target = None;
if let Some(position) = placeholder {
for (run_index, run) in line.runs.iter().enumerate() {
let len = run.text.chars().count();
if (run_start..run_start + len).contains(&position)
&& run.text.chars().nth(position - run_start) == Some(' ')
{
target = Some((run_index, position - run_start));
break;
}
run_start += len;
}
}
match target {
Some((run_index, local)) => {
let run = line.runs.remove(run_index);
let chars: Vec<char> = run.text.chars().collect();
let mut pieces = Vec::with_capacity(3);
if local > 0 {
let mut before = run.clone();
before.text = chars[..local].iter().collect();
before.display_text = None;
before.footnote_marker = None;
pieces.push(before);
}
let mut number = run.clone();
number.text = " ".to_string();
number.display_text = Some(number_text.trim_end().to_string());
number.footnote_marker = number_marker;
pieces.push(number);
if local + 1 < chars.len() {
let mut after = run;
after.text = chars[local + 1..].iter().collect();
after.display_text = None;
after.footnote_marker = None;
pieces.push(after);
}
for (offset, piece) in pieces.into_iter().enumerate() {
line.runs.insert(run_index + offset, piece);
}
}
None => {
let mut number = line.runs.first().cloned().unwrap_or_default();
number.text = number_text.to_string();
number.char_style_id = base_cs_id;
number.display_text = None;
number.footnote_marker = number_marker;
number.char_overlap = None;
number.inserted_control_text = true;
line.runs.insert(0, number);
}
}
Some(numbered)
}
fn shrink_footnote_number(nodes: &mut [RenderNode], number: &str) {
for line in nodes
.iter_mut()
.filter(|node| matches!(node.node_type, RenderNodeType::TextLine(_)))
{
let Some(index) = line.children.iter().position(|child| {
matches!(&child.node_type, RenderNodeType::TextRun(run)
if run.display_or_text().trim_end() == number)
}) else {
continue;
};
let node = &mut line.children[index];
let RenderNodeType::TextRun(run) = &mut node.node_type else {
return;
};
let base = run.style.font_size;
let (size, baseline) =
crate::renderer::script_metrics::ScriptMetricsContract::NoteReference.draw_metrics(
base,
run.baseline,
true,
false,
run.style.font_position,
);
run.style.font_size = size;
run.baseline = baseline;
run.style.superscript = false;
run.style.subscript = false;
run.style.font_position = None;
run.layout_positions = None;
let width = estimate_text_width(run.display_or_text(), &run.style);
let dx = node.bbox.width - width;
node.bbox.width = width;
for next in &mut line.children[index + 1..] {
if matches!(next.node_type, RenderNodeType::TextRun(_)) {
next.bbox.x -= dx;
}
}
return;
}
}
fn footnote_composed_line_count(
paragraphs: &[Paragraph],
content_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
) -> usize {
paragraphs
.iter()
.map(|paragraph| {
compose_footnote_paragraph(paragraph, content_width_px, styles, dpi)
.lines
.len()
.max(1)
})
.sum()
}
fn rotated_frame_node_box(
pic_x: f64,
pic_y: f64,
pic_width: f64,
pic_height: f64,
size: (f64, f64),
) -> BoundingBox {
let (width, height) = size;
let center_x = pic_x + pic_width / 2.0;
let center_y = pic_y + pic_height / 2.0;
BoundingBox::new(
center_x - width / 2.0,
center_y - height / 2.0,
width,
height,
)
}
impl LayoutEngine {
#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_picture_full(
&self,
tree: &mut PageLayoutContext,
parent_node: &mut RenderNode,
picture: &crate::model::image::Picture,
container: &LayoutRect,
bin_data_content: &[BinDataContent],
alignment: Alignment,
section_index: Option<usize>,
para_index: Option<usize>,
control_index: Option<usize>,
header_footer_ref: Option<crate::renderer::render_tree::HeaderFooterImageRef>,
cell_ctx: Option<&crate::renderer::layout::CellContext>,
styles: &ResolvedStyleSet,
) {
let rotation = picture.shape_attr.rotation_angle.rem_euclid(360);
let uses_rotated_frame = rotation != 0
&& picture.shape_attr.current_width > 0
&& picture.shape_attr.current_height > 0
&& picture.common.width > 0
&& picture.common.height > 0;
let (pic_width_hu, pic_height_hu) = if uses_rotated_frame {
(
picture.shape_attr.current_width as i32,
picture.shape_attr.current_height as i32,
)
} else {
picture_display_size_hu(picture)
};
let mut pic_width = hwpunit_to_px(pic_width_hu, self.dpi);
let mut pic_height = hwpunit_to_px(pic_height_hu, self.dpi);
let mut frame_width = if uses_rotated_frame {
hwpunit_to_px(picture.common.width as i32, self.dpi)
} else {
pic_width
};
let mut frame_height = if uses_rotated_frame {
hwpunit_to_px(picture.common.height as i32, self.dpi)
} else {
pic_height
};
let preserve_inline_cell_frame = picture.common.treat_as_char && cell_ctx.is_some();
if !preserve_inline_cell_frame {
if container.width > 0.0 && frame_width > container.width {
let scale = container.width / frame_width;
frame_width = container.width;
frame_height *= scale;
pic_width *= scale;
pic_height *= scale;
}
if container.height > 0.0 && frame_height > container.height {
let scale = container.height / frame_height;
frame_height = container.height;
frame_width *= scale;
pic_height *= scale;
pic_width *= scale;
}
}
let node_box_size = if uses_rotated_frame {
(frame_width, frame_height)
} else {
(pic_width, pic_height)
};
let caption_band_height =
crate::renderer::composer::caption_height_px(&picture.caption, self.dpi);
let caption_spacing = picture
.caption
.as_ref()
.map(|c| hwpunit_to_px(c.spacing as i32, self.dpi))
.unwrap_or(0.0);
let (caption_top_offset, caption_left_offset, caption_band_width) =
match picture.caption.as_ref().map(|c| c.direction) {
Some(CaptionDirection::Top) => (caption_band_height + caption_spacing, 0.0, 0.0),
Some(CaptionDirection::Left) => {
let cw = picture
.caption
.as_ref()
.map(|c| hwpunit_to_px(c.width as i32, self.dpi))
.unwrap_or(0.0);
(0.0, cw + caption_spacing, cw + caption_spacing)
}
Some(CaptionDirection::Right) => {
let cw = picture
.caption
.as_ref()
.map(|c| hwpunit_to_px(c.width as i32, self.dpi))
.unwrap_or(0.0);
(0.0, 0.0, cw + caption_spacing)
}
_ => (0.0, 0.0, 0.0),
};
let caption_block_extra_height = match picture.caption.as_ref().map(|c| c.direction) {
Some(CaptionDirection::Top) | Some(CaptionDirection::Bottom) => {
caption_band_height + caption_spacing
}
_ => 0.0,
};
let block_width = frame_width + caption_band_width;
let block_height = frame_height + caption_block_extra_height;
let (pic_x, pic_y) = if !picture.common.treat_as_char {
let h_offset = hwpunit_to_px(picture.common.horizontal_offset as i32, self.dpi);
let v_offset = hwpunit_to_px(picture.common.vertical_offset as i32, self.dpi);
let frame_x = match picture.common.horz_align {
HorzAlign::Left | HorzAlign::Inside => container.x + h_offset,
HorzAlign::Center => container.x + (container.width - block_width) / 2.0 + h_offset,
HorzAlign::Right | HorzAlign::Outside => {
container.x + container.width - block_width - h_offset
}
};
let frame_y = match picture.common.vert_align {
VertAlign::Top | VertAlign::Inside => container.y + v_offset,
VertAlign::Center => {
container.y + (container.height - block_height) / 2.0 + v_offset
}
VertAlign::Bottom | VertAlign::Outside => {
container.y + container.height - block_height - v_offset
}
};
(
frame_x + caption_left_offset + (frame_width - pic_width) / 2.0,
frame_y + caption_top_offset + (frame_height - pic_height) / 2.0,
)
} else {
let frame_x = match alignment {
Alignment::Center | Alignment::Distribute => {
container.x + (container.width - block_width).max(0.0) / 2.0
}
Alignment::Right => container.x + (container.width - block_width).max(0.0),
_ => container.x,
};
(
frame_x + caption_left_offset + (frame_width - pic_width) / 2.0,
container.y + caption_top_offset + (frame_height - pic_height) / 2.0,
)
};
let bin_data_id = picture.image_attr.bin_data_id;
let image_data = find_bin_data_bytes(bin_data_content, bin_data_id);
if picture_data_is_unusable(image_data.as_deref())
&& picture.image_attr.external_path.is_none()
{
let ph_id = tree.next_id();
parent_node.children.push(RenderNode::new(
ph_id,
RenderNodeType::Placeholder(
crate::renderer::render_tree::PlaceholderNode::missing_picture(
section_index,
para_index,
control_index,
cell_ctx.cloned(),
),
),
rotated_frame_node_box(pic_x, pic_y, pic_width, pic_height, node_box_size),
));
return;
}
let crop = picture.render_crop_rect();
let original_size_hu = picture.crop_reference_size();
let (cei, cpi, otci) = cell_ctx
.map(|c| c.last_image_indices())
.unwrap_or((None, None, None));
let img_id = tree.next_id();
let mut img_node = RenderNode::new(
img_id,
RenderNodeType::Image(ImageNode {
section_index,
para_index,
control_index,
crop,
original_size_hu,
effect: picture.image_attr.effect,
brightness: picture.image_attr.brightness,
contrast: picture.image_attr.contrast,
opacity: picture.image_attr.opacity(),
text_wrap: Some(picture.common.text_wrap),
transform: crate::renderer::image_geometry::picture_transform(picture),
external_path: picture.image_attr.external_path.clone(),
content_inset: crate::renderer::layout::utils::picture_content_inset(picture),
pre_rotation_ratio: crate::renderer::image_geometry::picture_pre_rotation_ratio(
picture,
),
source_rect: crate::renderer::image_geometry::picture_source_rect(picture),
header_footer_ref: header_footer_ref.clone(),
cell_index: cei,
cell_para_index: cpi,
outer_table_control_index: otci,
cell_context: cell_ctx.cloned(),
..ImageNode::new(bin_data_id, image_data)
}),
rotated_frame_node_box(pic_x, pic_y, pic_width, pic_height, node_box_size),
);
img_node.source_inline_picture = picture.common.treat_as_char;
self.append_picture_image_node(tree, parent_node, picture, img_node);
if let Some(ref caption) = picture.caption {
use crate::model::shape::CaptionVertAlign;
let (cap_x, cap_w, cap_y) = match caption.direction {
CaptionDirection::Top => (
pic_x,
pic_width,
(pic_y - caption_top_offset).max(container.y),
),
CaptionDirection::Bottom => {
(pic_x, pic_width, pic_y + pic_height + caption_spacing)
}
CaptionDirection::Left | CaptionDirection::Right => {
let cw = hwpunit_to_px(caption.width as i32, self.dpi);
let cx = if caption.direction == CaptionDirection::Left {
pic_x - caption_left_offset
} else {
pic_x + pic_width + caption_spacing
};
let cy = match caption.vert_align {
CaptionVertAlign::Top => pic_y,
CaptionVertAlign::Center => {
pic_y + (pic_height - caption_band_height).max(0.0) / 2.0
}
CaptionVertAlign::Bottom => {
pic_y + (pic_height - caption_band_height).max(0.0)
}
};
(cx, cw, cy)
}
};
let caption_cell_ctx = cell_ctx.cloned().or_else(|| {
para_index.map(|pi| super::CellContext {
in_textbox: false,
parent_para_index: pi,
path: vec![super::CellPathEntry {
control_index: control_index.unwrap_or(0),
cell_index: 0,
cell_para_index: 0,
text_direction: 0,
}],
})
});
self.layout_caption(
tree,
parent_node,
caption,
styles,
container,
cap_x,
cap_w,
cap_y,
&mut self.auto_counter.borrow_mut(),
bin_data_content,
caption_cell_ctx,
CaptionOwner::new(
section_index,
para_index,
control_index,
CaptionControlKind::Image,
),
);
}
if picture.common.treat_as_char {
if let (Some(sec), Some(para_for_layout), Some(ctrl)) =
(section_index, para_index, control_index)
{
tree.set_inline_shape_position(sec, para_for_layout, ctrl, cell_ctx, pic_x, pic_y);
}
}
}
pub(crate) fn resolve_object_size(
&self,
common: &CommonObjAttr,
col_area: &LayoutRect,
body_area: &LayoutRect,
paper_area: &LayoutRect,
) -> (f64, f64) {
use crate::model::shape::SizeCriterion;
let raw_w = common.width as f64;
let raw_h = common.height as f64;
let obj_width = match common.width_criterion {
SizeCriterion::Absolute => hwpunit_to_px(common.width as i32, self.dpi),
SizeCriterion::Paper => paper_area.width * raw_w / 10000.0,
SizeCriterion::Page => body_area.width * raw_w / 10000.0,
SizeCriterion::Column => col_area.width * raw_w / 10000.0,
SizeCriterion::Para => col_area.width * raw_w / 10000.0,
};
let obj_height = match common.height_criterion {
SizeCriterion::Absolute => hwpunit_to_px(common.height as i32, self.dpi),
SizeCriterion::Paper => paper_area.height * raw_h / 10000.0,
SizeCriterion::Page => body_area.height * raw_h / 10000.0,
_ => hwpunit_to_px(common.height as i32, self.dpi),
};
(obj_width, obj_height)
}
pub(crate) fn compute_object_position(
&self,
common: &CommonObjAttr,
obj_width: f64,
obj_height: f64,
container: &LayoutRect,
col_area: &LayoutRect,
body_area: &LayoutRect,
paper_area: &LayoutRect,
para_y: f64,
alignment: Alignment,
) -> (f64, f64) {
crate::renderer::float_placement::ObjectPlacementFrame {
container,
column: col_area,
body: body_area,
paper: paper_area,
paragraph_y: para_y,
alignment,
dpi: self.dpi,
}
.position(common, obj_width, obj_height)
}
pub(crate) fn layout_body_picture(
&self,
tree: &mut PageLayoutContext,
parent_node: &mut RenderNode,
picture: &crate::model::image::Picture,
container: &LayoutRect,
col_area: &LayoutRect,
body_area: &LayoutRect,
paper_area: &LayoutRect,
bin_data_content: &[BinDataContent],
styles: &ResolvedStyleSet,
alignment: Alignment,
y_offset: f64,
section_index: usize,
para_index: usize,
control_index: usize,
vpos_accounts_for_height: bool,
) -> BodyPicturePlacement {
let (pic_width_hu, pic_height_hu) = super::utils::picture_flow_frame_size_hu(picture);
let pic_width = hwpunit_to_px(pic_width_hu, self.dpi);
let pic_height = hwpunit_to_px(pic_height_hu, self.dpi);
let caption_height = self.calculate_caption_height(&picture.caption, styles);
let caption_spacing = if let Some(ref caption) = picture.caption {
hwpunit_to_px(caption.spacing as i32, self.dpi)
} else {
0.0
};
let outer_box = crate::renderer::float_placement::picture_outer_box(
picture,
pic_width,
pic_height,
caption_height,
self.dpi,
);
let box_width = outer_box.width;
let box_height = outer_box.height;
let margin_left = outer_box.margin_left;
let margin_top = outer_box.margin_top;
let (box_x, base_y) = self.compute_object_position(
&picture.common,
box_width,
box_height,
container,
col_area,
body_area,
paper_area,
y_offset,
alignment,
);
let base_y = if !picture.common.treat_as_char
&& picture.common.flow_with_text
&& !vpos_accounts_for_height
&& matches!(picture.common.vert_rel_to, VertRelTo::Para)
{
let body_bottom = col_area.y + col_area.height - box_height;
base_y.min(body_bottom.max(col_area.y))
} else {
base_y
};
let caption_top_offset = outer_box.caption_top;
let caption_left_offset = outer_box.caption_left;
let adjusted_pic_x = box_x + margin_left + caption_left_offset;
let vpos_shift = if vpos_accounts_for_height {
box_height
} else {
0.0
};
let content_top = base_y + margin_top - vpos_shift;
let pic_y = content_top + caption_top_offset;
let bin_data_id = picture.image_attr.bin_data_id;
let image_data = find_bin_data_bytes(bin_data_content, bin_data_id);
let picture_missing = picture_data_is_unusable(image_data.as_deref())
&& picture.image_attr.external_path.is_none();
let crop = picture.render_crop_rect();
let original_size_hu = picture.crop_reference_size();
let img_id = tree.next_id();
let node_type = if picture_missing {
RenderNodeType::Placeholder(
crate::renderer::render_tree::PlaceholderNode::missing_picture(
Some(section_index),
Some(para_index),
Some(control_index),
None,
),
)
} else {
RenderNodeType::Image(ImageNode {
section_index: Some(section_index),
para_index: Some(para_index),
control_index: Some(control_index),
crop,
original_size_hu,
effect: picture.image_attr.effect,
brightness: picture.image_attr.brightness,
contrast: picture.image_attr.contrast,
opacity: picture.image_attr.opacity(),
text_wrap: Some(picture.common.text_wrap),
transform: crate::renderer::image_geometry::picture_transform(picture),
external_path: picture.image_attr.external_path.clone(),
content_inset: crate::renderer::layout::utils::picture_content_inset(picture),
pre_rotation_ratio: crate::renderer::image_geometry::picture_pre_rotation_ratio(
picture,
),
source_rect: crate::renderer::image_geometry::picture_source_rect(picture),
..ImageNode::new(bin_data_id, image_data)
})
};
let img_node = RenderNode::new(
img_id,
node_type,
BoundingBox::new(adjusted_pic_x, pic_y, pic_width, pic_height),
);
parent_node.children.push(img_node);
let mut content_bottom = pic_y + pic_height;
self.render_picture_border(
tree,
parent_node,
picture,
img_id,
adjusted_pic_x,
pic_y,
pic_width,
pic_height,
);
if let Some(ref caption) = picture.caption {
use crate::model::shape::CaptionVertAlign;
let (cap_x, cap_w, cap_y) = match caption.direction {
CaptionDirection::Top => (adjusted_pic_x, pic_width, base_y + margin_top),
CaptionDirection::Bottom => (
adjusted_pic_x,
pic_width,
pic_y + pic_height + caption_spacing,
),
CaptionDirection::Left | CaptionDirection::Right => {
let cw = hwpunit_to_px(caption.width as i32, self.dpi);
let cx = if caption.direction == CaptionDirection::Left {
box_x + margin_left
} else {
adjusted_pic_x + pic_width + caption_spacing
};
let cy = match caption.vert_align {
CaptionVertAlign::Top => pic_y,
CaptionVertAlign::Center => {
pic_y + (pic_height - caption_height).max(0.0) / 2.0
}
CaptionVertAlign::Bottom => pic_y + (pic_height - caption_height).max(0.0),
};
(cx, cw, cy)
}
};
content_bottom = content_bottom.max(cap_y + caption_height);
let cell_ctx = super::CellContext {
in_textbox: false,
parent_para_index: para_index,
path: vec![super::CellPathEntry {
control_index,
cell_index: 0,
cell_para_index: 0,
text_direction: 0,
}],
};
self.layout_caption(
tree,
parent_node,
caption,
styles,
col_area,
cap_x,
cap_w,
cap_y,
&mut self.auto_counter.borrow_mut(),
bin_data_content,
Some(cell_ctx),
CaptionOwner::new(
Some(section_index),
Some(para_index),
Some(control_index),
CaptionControlKind::Image,
),
);
}
let flow_end = match (picture.common.vert_rel_to, picture.common.text_wrap) {
(VertRelTo::Para, TextWrap::BehindText | TextWrap::InFrontOfText) => y_offset,
(VertRelTo::Para, _) if vpos_accounts_for_height => base_y,
(VertRelTo::Para, _) => base_y + box_height,
(VertRelTo::Page | VertRelTo::Paper, _) => y_offset,
};
BodyPicturePlacement {
flow_end,
content_bottom,
}
}
pub(crate) fn calculate_caption_height(
&self,
caption: &Option<Caption>,
styles: &ResolvedStyleSet,
) -> f64 {
super::super::composer::caption_height_px_in_context(caption, Some(styles), self.dpi)
}
pub(crate) fn layout_caption(
&self,
tree: &mut PageLayoutContext,
parent_node: &mut RenderNode,
caption: &Caption,
styles: &ResolvedStyleSet,
_col_area: &LayoutRect,
content_x: f64,
content_width: f64,
y_start: f64,
_auto_counter: &mut AutoNumberCounter,
bin_data_content: &[BinDataContent],
cell_ctx: Option<super::CellContext>,
caption_owner: Option<CaptionOwner>,
) {
if caption.paragraphs.is_empty() {
return;
}
let caption_area = LayoutRect {
x: content_x,
y: y_start,
width: content_width,
height: 0.0, };
let mut para_y = y_start;
for (pi, para) in caption.paragraphs.iter().enumerate() {
let first_caption_node = parent_node.children.len();
let para_y_before_layout = para_y;
let mut composed =
crate::renderer::composer::compose_paragraph_in_context(para, styles);
crate::renderer::composer::project_caption_auto_numbers(&mut composed, para);
let ctx = cell_ctx.as_ref().map(|c| {
let mut cc = c.clone();
if let Some(last) = cc.path.last_mut() {
last.cell_para_index = pi;
}
cc
});
para_y = self.layout_composed_paragraph(
tree,
parent_node,
&composed,
styles,
&caption_area,
para_y,
0,
composed.lines.len(),
0,
0,
ctx.clone(),
false,
false,
0.0,
None,
Some(para),
Some(bin_data_content),
None, );
for node in &mut parent_node.children[first_caption_node..] {
if let RenderNodeType::TextLine(line) = &mut node.node_type {
line.caption_owner = caption_owner.map(|owner| CaptionOwner {
caption_ordinal: pi,
..owner
});
}
}
self.layout_caption_topbottom_pictures(
tree,
parent_node,
para,
&caption_area,
para_y_before_layout,
bin_data_content,
ctx.as_ref(),
styles,
);
}
}
fn layout_caption_topbottom_pictures(
&self,
tree: &mut PageLayoutContext,
parent_node: &mut RenderNode,
para: &Paragraph,
caption_area: &LayoutRect,
para_y: f64,
bin_data_content: &[BinDataContent],
cell_ctx: Option<&super::CellContext>,
styles: &ResolvedStyleSet,
) {
let anchor_y = para
.line_segs
.first()
.filter(|seg| seg.vertical_pos >= 0)
.map(|seg| caption_area.y + hwpunit_to_px(seg.vertical_pos, self.dpi))
.unwrap_or(para_y);
for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
let Control::Picture(pic) = ctrl else {
continue;
};
if !matches!(pic.common.text_wrap, TextWrap::TopAndBottom) {
continue;
}
if tree
.get_inline_shape_position(0, 0, ctrl_idx, cell_ctx)
.is_some()
{
continue;
}
let (pic_width_hu, pic_height_hu) = picture_display_size_hu(pic);
let pic_width = hwpunit_to_px(pic_width_hu, self.dpi);
let pic_height = hwpunit_to_px(pic_height_hu, self.dpi);
let placement_area = LayoutRect {
x: caption_area.x,
y: anchor_y,
width: caption_area.width,
height: pic_height.max(caption_area.height),
};
let mut placement_common = pic.common.clone();
placement_common.treat_as_char = false;
let (pic_x, pic_y) = self.compute_object_position(
&placement_common,
pic_width,
pic_height,
&placement_area,
&placement_area,
&placement_area,
&placement_area,
anchor_y,
Alignment::Left,
);
let pic_area = LayoutRect {
x: pic_x,
y: pic_y,
width: pic_width,
height: pic_height,
};
let mut pic_for_layout = (**pic).clone();
pic_for_layout.common.treat_as_char = false;
pic_for_layout.common.horizontal_offset = 0;
pic_for_layout.common.vertical_offset = 0;
pic_for_layout.common.horz_align = HorzAlign::Left;
pic_for_layout.common.vert_align = VertAlign::Top;
self.layout_picture(
tree,
parent_node,
&pic_for_layout,
&pic_area,
bin_data_content,
Alignment::Left,
Some(0),
Some(0),
Some(ctrl_idx),
cell_ctx,
styles,
);
if pic.common.treat_as_char {
tree.set_inline_shape_position(0, 0, ctrl_idx, cell_ctx, pic_x, pic_y);
}
}
}
fn footnote_line_metrics(
&self,
comp_line: &ComposedLine,
para_style_id: u16,
styles: &ResolvedStyleSet,
) -> (f64, f64) {
let raw_lh = hwpunit_to_px(comp_line.line_height, self.dpi);
let raw_ls = hwpunit_to_px(comp_line.line_spacing, self.dpi);
let max_fs = comp_line
.runs
.iter()
.map(|run| run.line_box_font_size(styles))
.fold(0.0f64, f64::max);
let para_style = styles.para_styles.get(para_style_id as usize);
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(LineSpacingType::Percent);
crate::renderer::corrected_line_metrics(raw_lh, raw_ls, max_fs, ls_type, ls_val)
}
fn footnote_block_table<'a>(
para: &'a Paragraph,
selected: &std::ops::Range<usize>,
) -> Option<&'a crate::model::table::Table> {
let [Control::Table(table)] = para.controls.as_slice() else {
return None;
};
if selected.start != 0
|| selected.end == 0
|| para
.text
.chars()
.any(|ch| !ch.is_whitespace() && ch != '\u{fffc}')
|| !matches!(table.common.text_wrap, TextWrap::TopAndBottom)
|| !matches!(table.common.vert_rel_to, VertRelTo::Para)
|| !matches!(table.common.vert_align, VertAlign::Top | VertAlign::Inside)
|| table.caption.is_some()
|| table.row_count == 0
|| table.col_count == 0
{
return None;
}
if table.common.treat_as_char {
let seg_width = para.line_segs.first().map_or(0, |line| line.segment_width);
if para.stored_text_partition_is_dirty()
|| !Self::tac_stored_band_is_outer_box(para, table)
|| crate::renderer::height_measurer::is_tac_table_inline_in_para(
table, seg_width, para,
)
{
return None;
}
}
Some(table)
}
fn footnote_block_table_frame<'a>(
&self,
para: &'a Paragraph,
composed: &ComposedParagraph,
styles: &ResolvedStyleSet,
selected: &std::ops::Range<usize>,
area_width: f64,
) -> Option<FootnoteBlockTableFrame<'a>> {
let table = Self::footnote_block_table(para, selected)?;
let measurer = crate::renderer::height_measurer::HeightMeasurer::new(self.dpi)
.with_hwp3_variant(self.profile.get().hwp3_layout())
.with_stored_geometry_policy(self.profile.get().stored_geometry_policy())
.with_native_hwp5(self.profile.get().hwp5_stored_pagination_layout())
.with_hwpx_stored_layout(self.profile.get().hwpx_stored_layout())
.with_session_edited(self.profile.get().session_edited())
.with_render_normalization(self.render_normalization_overlay());
let measured = measurer.measure_table(table, 0, 0, styles);
let rows = self.resolve_row_heights(
table,
table.col_count as usize,
table.row_count as usize,
Some(&measured),
styles,
table.common.treat_as_char,
);
let body_height = rows.iter().sum::<f64>()
+ measured.cell_spacing * (table.row_count as usize + 1) as f64;
let top_offset = if table.common.treat_as_char {
self.tac_table_stored_outer_band_top(para, table, body_height, 0.0)?
} else {
hwpunit_to_px(table.common.vertical_offset as i32, self.dpi)
+ hwpunit_to_px(table.outer_margin_top as i32, self.dpi)
};
let mut advance =
top_offset + body_height + hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi);
let (trailing_line_spacing, line_left_offset) = if table.common.treat_as_char {
let line = composed.lines.first()?;
let (line_height, line_spacing) =
self.footnote_line_metrics(line, composed.para_style_id, styles);
advance = advance.max(line_height);
let style = styles.para_styles.get(composed.para_style_id as usize);
let margin_left = style.map_or(0.0, |style| style.margin_left);
let right = style.map_or(0.0, |style| style.margin_right);
let indent = crate::renderer::equation_tac_flow::paragraph_line_indent_for_source(
style.map_or(0.0, |style| style.indent),
0,
Some(para),
composed.lines.len(),
true,
area_width - margin_left - right,
self.dpi,
);
let left = margin_left + indent;
let outer_left = hwpunit_to_px(table.outer_margin_left as i32, self.dpi);
let outer_right = hwpunit_to_px(table.outer_margin_right as i32, self.dpi);
let width = self
.resolve_column_widths(table, table.col_count as usize)
.iter()
.sum::<f64>()
+ measured.cell_spacing * (table.col_count as usize + 1) as f64;
let slack = (area_width - left - right - width - outer_left - outer_right).max(0.0);
let aligned = match style.map_or(Alignment::Left, |style| style.alignment) {
Alignment::Center | Alignment::Distribute => slack / 2.0,
Alignment::Right => slack,
_ => 0.0,
};
(line_spacing, Some(left + aligned + outer_left))
} else {
(0.0, None)
};
Some(FootnoteBlockTableFrame {
table,
measured,
top_offset,
advance,
trailing_line_spacing,
line_left_offset,
})
}
#[allow(clippy::too_many_arguments)]
fn footnote_paragraph_placement<'a>(
&self,
para: &'a Paragraph,
composed: &ComposedParagraph,
styles: &ResolvedStyleSet,
fragment: Option<FootnoteFragment>,
number_drawn: bool,
selected: std::ops::Range<usize>,
relative_y: f64,
area_width: f64,
) -> FootnoteParagraphPlacement<'a> {
let mut block_table = (composed.lines.len() <= 1)
.then(|| self.footnote_block_table_frame(para, composed, styles, &selected, area_width))
.flatten();
let route = if para.text.is_empty()
&& para.controls.is_empty()
&& !fragment_draws_number(fragment)
&& composed.lines.len() == 1
{
FootnoteParagraphRoute::StoredEmpty
} else if fragment_draws_number(fragment) && !number_drawn {
FootnoteParagraphRoute::Numbered
} else {
FootnoteParagraphRoute::Plain
};
let mut spacing = ParagraphVerticalSpacing {
before: 0.0,
after: 0.0,
};
if route == FootnoteParagraphRoute::Plain {
let style = styles.para_styles.get(composed.para_style_id as usize);
if selected.start == 0 && relative_y.abs() >= 1.0 {
spacing.before = crate::renderer::hwp3_variant_flow_spacing_before(
style.map_or(0.0, |style| style.spacing_before),
self.use_hwp3_origin_flow_spacing_before.get(),
)
.max(0.0);
}
if selected.end == composed.lines.len().max(1) {
spacing.after = style.map_or(0.0, |style| style.spacing_after).max(0.0);
}
}
if route == FootnoteParagraphRoute::Numbered {
if let Some(block) = block_table.as_mut() {
let number_line_height = composed.lines.first().map_or_else(
|| hwpunit_to_px(400, self.dpi),
|line| {
self.footnote_line_metrics(line, composed.para_style_id, styles)
.0
},
);
block.advance = block.advance.max(number_line_height);
}
}
FootnoteParagraphPlacement {
route,
spacing,
block_table,
}
}
pub(crate) fn footnote_area_has_stored_lines(
&self,
footnotes: &[FootnoteRef],
paragraphs: &[Paragraph],
area_width: f64,
) -> bool {
let width_hu = i64::from(crate::renderer::px_to_hwpunit(area_width, self.dpi));
!footnotes.is_empty()
&& footnotes.iter().all(|note| {
let paras = get_footnote_paragraphs(note, paragraphs);
!paras.is_empty()
&& paras.iter().all(|para| {
!para.line_segs.is_empty()
&& !para.stored_text_partition_is_dirty()
&& para.line_segs.iter().all(|line| {
line.line_height > 0
&& line.segment_width > 0
&& i64::from(line.column_start) + i64::from(line.segment_width)
<= width_hu
&& line.tag
& crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
== 0
})
})
})
}
pub(crate) fn estimate_footnote_area_height(
&self,
footnotes: &[FootnoteRef],
paragraphs: &[Paragraph],
shape: &FootnoteShape,
styles: &ResolvedStyleSet,
area_width: f64,
) -> f64 {
self.estimate_footnote_area_height_with_metrics(
footnotes,
paragraphs,
styles,
area_width,
hwpunit_to_px(shape.separator_above_margin_hu() as i32, self.dpi)
+ border_width_to_px(shape.separator_line_width).max(0.5)
+ hwpunit_to_px(shape.separator_below_margin_hu() as i32, self.dpi),
hwpunit_to_px(shape.between_notes_margin_hu() as i32, self.dpi),
)
}
pub(crate) fn estimate_footnote_area_height_with_metrics(
&self,
footnotes: &[FootnoteRef],
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
area_width: f64,
separator_height: f64,
between_notes: f64,
) -> f64 {
if footnotes.is_empty() {
return 0.0;
}
let mut total = if footnotes
.iter()
.any(|note| fragment_draws_separator(note.fragment))
{
separator_height
} else {
0.0
};
for (i, fn_ref) in footnotes.iter().enumerate() {
let fn_paras = get_footnote_paragraphs(fn_ref, paragraphs);
total += self.footnote_paragraphs_content_height(
fn_paras,
styles,
area_width,
fn_ref.fragment,
total,
);
if i + 1 < footnotes.len() {
total += between_notes;
}
}
total
}
pub(crate) fn footnote_paragraphs_content_height(
&self,
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
area_width: f64,
fragment: Option<FootnoteFragment>,
origin_y: f64,
) -> f64 {
let (start_line, end_line) = fragment_line_bounds(
fragment,
footnote_composed_line_count(paragraphs, area_width, styles, self.dpi),
);
let mut total = origin_y;
let mut flat_line = 0usize;
let mut number_drawn = false;
for para in paragraphs {
let composed = compose_footnote_paragraph(para, area_width, styles, self.dpi);
let line_count = composed.lines.len().max(1);
let para_start = flat_line;
let selected_start = start_line.saturating_sub(para_start).min(line_count);
let selected_end = end_line.saturating_sub(para_start).min(line_count);
flat_line += line_count;
if selected_start >= selected_end {
continue;
}
let placement = self.footnote_paragraph_placement(
para,
&composed,
styles,
fragment,
number_drawn,
selected_start..selected_end,
total,
area_width,
);
total += placement.spacing.before;
if let Some(block) = placement.block_table {
total += block.advance;
if para_start + selected_end < end_line {
total += block.trailing_line_spacing;
}
} else if placement.route == FootnoteParagraphRoute::StoredEmpty {
total += hwpunit_to_px(composed.lines[0].line_height, self.dpi);
} else if composed.lines.is_empty() {
total += hwpunit_to_px(400, self.dpi);
} else {
for (index, line) in composed.lines[selected_start..selected_end]
.iter()
.enumerate()
{
let (height, spacing) =
self.footnote_line_metrics(line, composed.para_style_id, styles);
total += height;
if para_start + selected_start + index + 1 < end_line {
total += spacing;
}
}
}
total += placement.spacing.after;
number_drawn |= placement.route == FootnoteParagraphRoute::Numbered;
}
total - origin_y
}
pub(crate) fn footnote_with_block_table_content_height(
&self,
footnote: &crate::model::footnote::Footnote,
styles: &ResolvedStyleSet,
area_width: f64,
fragment: Option<FootnoteFragment>,
) -> Option<f64> {
footnote
.paragraphs
.iter()
.any(|para| {
Self::footnote_block_table(para, &(0..1)).is_some()
&& compose_footnote_paragraph(para, area_width, styles, self.dpi)
.lines
.len()
<= 1
})
.then(|| {
self.footnote_paragraphs_content_height(
&footnote.paragraphs,
styles,
area_width,
fragment,
0.0,
)
})
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_footnote_area(
&self,
tree: &mut PageLayoutContext,
fn_node: &mut RenderNode,
footnotes: &[FootnoteRef],
paragraphs: &[Paragraph],
styles: &ResolvedStyleSet,
fn_area: &LayoutRect,
shape: &FootnoteShape,
source_indices: &[usize],
bin_data_content: &[BinDataContent],
) {
let mut y = fn_area.y;
if footnotes
.iter()
.any(|footnote| fragment_draws_separator(footnote.fragment))
{
y += hwpunit_to_px(shape.separator_above_margin_hu() as i32, self.dpi);
let sep_length =
footnote_separator_length_px(shape.separator_length, fn_area.width, self.dpi);
let line_width = border_width_to_px(shape.separator_line_width).max(0.5);
super::note_separator::append(
tree, fn_node, shape, fn_area.x, y, sep_length, line_width,
);
y += line_width;
y += hwpunit_to_px(shape.separator_below_margin_hu() as i32, self.dpi);
}
for (frame_index, fn_ref) in footnotes.iter().enumerate() {
let i = source_indices[frame_index];
let fn_paras = get_footnote_paragraphs(fn_ref, paragraphs);
let number_text = format_footnote_number(
fn_ref.number,
&shape.number_format,
shape.prefix_char,
shape.suffix_char,
shape.user_char,
);
let (fragment_start, fragment_end) = fragment_line_bounds(
fn_ref.fragment,
footnote_composed_line_count(fn_paras, fn_area.width, styles, self.dpi),
);
let mut flat_line = 0usize;
let mut number_drawn = false;
for (p_idx, para) in fn_paras.iter().enumerate() {
let composed = compose_footnote_paragraph(para, fn_area.width, styles, self.dpi);
let marker_section = i; let marker_para = usize::MAX - 2000 - p_idx; let base_cs_id = para
.char_shapes
.first()
.map(|cs| cs.char_shape_id as u32)
.unwrap_or(composed.para_style_id as u32);
let line_count = composed.lines.len().max(1);
let para_start = flat_line;
let para_end = flat_line + line_count;
let selected_start = fragment_start.saturating_sub(para_start).min(line_count);
let selected_end = fragment_end.saturating_sub(para_start).min(line_count);
flat_line = para_end;
if selected_start >= selected_end {
continue;
}
let is_last_selected_line = para_start + selected_end == fragment_end;
let placement = self.footnote_paragraph_placement(
para,
&composed,
styles,
fn_ref.fragment,
number_drawn,
selected_start..selected_end,
y - fn_area.y,
fn_area.width,
);
if let Some(block) = placement.block_table {
y += placement.spacing.before;
let anchor_y = y;
if placement.route == FootnoteParagraphRoute::Numbered {
let mut number_host = composed.clone();
if number_host.lines.is_empty() {
number_host.lines.push(ComposedLine {
runs: Vec::new(),
line_height: 400,
baseline_distance: 320,
segment_width: 0,
column_start: 0,
line_spacing: 0,
has_line_break: false,
char_start: 0,
});
}
self.layout_footnote_paragraph_with_number(
tree,
fn_node,
&number_host,
para,
styles,
fn_area,
anchor_y,
&number_text,
fn_ref.number,
marker_section,
marker_para,
base_cs_id,
selected_start,
selected_end,
true,
shape.number_code_superscript,
);
number_drawn = true;
}
let style = styles.para_styles.get(composed.para_style_id as usize);
self.layout_table(
tree,
fn_node,
block.table,
marker_section,
styles,
0,
fn_area,
anchor_y,
bin_data_content,
Some(&block.measured),
0,
Some((marker_para, 0)),
style.map_or(Alignment::Left, |style| style.alignment),
None,
style.map_or(0.0, |style| style.margin_left),
style.map_or(0.0, |style| style.margin_right),
None,
None,
Some(anchor_y),
None,
false,
false,
0.0,
Some((
block.line_left_offset.map(|offset| fn_area.x + offset),
anchor_y + block.top_offset,
)),
Self::standalone_table_char_border_fill(Some(para), block.table, styles),
);
y = anchor_y + block.advance + placement.spacing.after;
if !is_last_selected_line {
y += block.trailing_line_spacing;
}
continue;
}
if placement.route == FootnoteParagraphRoute::StoredEmpty {
y += hwpunit_to_px(composed.lines[0].line_height, self.dpi);
continue;
}
let draw_number = placement.route == FootnoteParagraphRoute::Numbered;
number_drawn |= draw_number;
let stored_prefix = (self.profile.get().hwpx_stored_layout()
|| self.profile.get().hwp5_stored_pagination_layout())
.then(|| stored_footnote_number_prefix(para, fn_ref.number))
.flatten();
let paragraph_number = stored_prefix
.as_ref()
.map_or(number_text.as_str(), |(text, _)| text.as_str());
let numbered = (draw_number
&& stored_prefix.as_ref().is_none_or(|(_, slots)| *slots <= 1))
.then(|| {
footnote_composed_with_number(
para,
&composed,
paragraph_number,
selected_start,
base_cs_id,
)
})
.flatten();
if !draw_number
&& composed.lines.len() == 1
&& selected_start == 0
&& selected_end == line_count
&& para.controls.iter().any(|control| {
matches!(control, Control::Table(table) if table.common.treat_as_char)
})
{
let style = styles.para_styles.get(composed.para_style_id as usize);
let before = crate::renderer::hwp3_variant_flow_spacing_before(
style.map_or(0.0, |style| style.spacing_before),
self.use_hwp3_origin_flow_spacing_before.get(),
);
let after = style.map_or(0.0, |style| style.spacing_after);
y = self.layout_inline_table_paragraph(
tree,
fn_node,
para,
Some(&composed),
styles,
fn_area,
y + placement.spacing.before - before,
marker_section,
marker_para,
bin_data_content,
&[],
).flow_bottom + placement.spacing.after - after;
if is_last_selected_line {
y -= hwpunit_to_px(composed.lines[0].line_spacing, self.dpi);
}
} else if draw_number && numbered.is_none() {
y = self.layout_footnote_paragraph_with_number(
tree,
fn_node,
&composed,
para,
styles,
fn_area,
y,
&number_text,
fn_ref.number,
marker_section,
marker_para,
base_cs_id,
selected_start,
selected_end,
is_last_selected_line,
shape.number_code_superscript,
);
} else {
let composed = numbered.as_ref().unwrap_or(&composed);
let first_new_child = fn_node.children.len();
let returned_y = self.layout_composed_paragraph_in_frame(
tree,
fn_node,
composed,
styles,
fn_area,
y,
selected_start,
selected_end,
marker_section,
marker_para,
None,
false,
false,
0.0,
None,
Some(para),
Some(bin_data_content),
None, false,
false,
Some(placement.spacing),
None,
);
if shape.number_code_superscript && numbered.is_some() {
shrink_footnote_number(
&mut fn_node.children[first_new_child..],
paragraph_number.trim_end(),
);
}
if is_last_selected_line {
let trail_ls = composed
.lines
.get(selected_end.saturating_sub(1))
.map(|l| hwpunit_to_px(l.line_spacing, self.dpi))
.unwrap_or(0.0);
y = returned_y - trail_ls;
} else {
y = returned_y;
}
}
}
if i + 1 < footnotes.len() {
y += hwpunit_to_px(shape.between_notes_margin_hu() as i32, self.dpi);
}
}
}
pub(crate) fn layout_footnote_paragraph_with_number(
&self,
tree: &mut PageLayoutContext,
parent: &mut RenderNode,
composed: &ComposedParagraph,
paragraph: &Paragraph,
styles: &ResolvedStyleSet,
area: &LayoutRect,
y_start: f64,
number_text: &str,
note_number: u16,
marker_section: usize,
marker_para: usize,
base_cs_id: u32,
line_start: usize,
line_end: usize,
is_last_selected_line: bool,
small_number: bool,
) -> f64 {
let mut y = y_start;
let stored_prefix = (self.profile.get().hwpx_stored_layout()
|| self.profile.get().hwp5_stored_pagination_layout())
.then(|| stored_footnote_number_prefix(paragraph, note_number))
.flatten();
let number_text = stored_prefix
.as_ref()
.map_or(number_text, |(text, _)| text.as_str());
let line_start = line_start.min(composed.lines.len());
let line_end = line_end.min(composed.lines.len()).max(line_start);
let para_style = styles.para_styles.get(composed.para_style_id as usize);
let margin_left = para_style.map(|style| style.margin_left).unwrap_or(0.0);
let margin_right = para_style.map(|style| style.margin_right).unwrap_or(0.0);
let indent = para_style.map(|style| style.indent).unwrap_or(0.0);
for (offset, comp_line) in composed.lines[line_start..line_end].iter().enumerate() {
let line_indent = crate::renderer::equation_tac_flow::paragraph_line_indent_for_source(
indent,
line_start + offset,
Some(paragraph),
composed.lines.len(),
true,
area.width - margin_left - margin_right,
self.dpi,
);
let line_x = area.x + margin_left + line_indent;
let line_width = (area.width - margin_left - margin_right - line_indent).max(0.0);
let (line_height, corrected_line_spacing) =
self.footnote_line_metrics(comp_line, composed.para_style_id, styles);
let raw_baseline = hwpunit_to_px(comp_line.baseline_distance, self.dpi);
let baseline = if line_height > 0.0
&& raw_baseline > 0.0
&& hwpunit_to_px(comp_line.line_height, self.dpi) > 0.0
{
(raw_baseline * line_height / hwpunit_to_px(comp_line.line_height, self.dpi))
.min(line_height)
} else {
raw_baseline
};
let line_id = tree.next_id();
let mut line_node = RenderNode::new(
line_id,
RenderNodeType::TextLine(TextLineNode::new(line_height, baseline)),
BoundingBox::new(line_x, y, line_width, line_height),
);
let mut x = line_x;
if offset == 0 {
let base_style = {
let mut ts = resolved_to_text_style(styles, base_cs_id, 0);
if small_number {
ts.font_size = FootnoteMarkerNode::font_size(ts.font_size);
} else if stored_prefix.is_none() {
ts.font_size = (ts.font_size * 0.9).max(8.0);
}
ts
};
let number_baseline = if small_number {
FootnoteMarkerNode::reference_baseline(
resolved_to_text_style(styles, base_cs_id, 0).font_size,
baseline,
)
} else {
baseline
};
let num_width = estimate_text_width(number_text, &base_style);
let num_id = tree.next_id();
let num_node = RenderNode::new(
num_id,
RenderNodeType::TextRun(TextRunNode {
text: number_text.to_string(),
style: base_style,
char_shape_id: None,
para_shape_id: None,
section_index: Some(marker_section),
para_index: Some(marker_para),
char_start: None, cell_context: None,
is_para_end: false,
is_line_break_end: false,
rotation: 0.0,
is_vertical: false,
char_overlap: None,
border_fill_id: 0,
baseline: number_baseline,
field_marker: FieldMarkerType::None,
layout_positions: None,
display_text: None,
}),
BoundingBox::new(x, y, num_width, line_height),
);
line_node.children.push(num_node);
x += num_width;
}
let mut char_offset = comp_line.char_start;
let mut tab_index = composed
.lines
.iter()
.take(line_start + offset)
.flat_map(|line| line.runs.iter())
.flat_map(|run| run.text.chars())
.filter(|&ch| ch == '\t')
.count();
for run in &comp_line.runs {
let mut text_style = run.text_style(styles);
let skipped = stored_prefix.as_ref().map_or(0, |(_, count)| {
count
.saturating_sub(char_offset)
.min(run.text.chars().count())
});
let text = run.text.chars().skip(skipped).collect::<String>();
if stored_prefix.is_some() {
text_style.inline_tabs = composed
.tab_extended
.iter()
.skip(tab_index)
.copied()
.collect();
}
let width = estimate_text_width(&text, &text_style);
tab_index += run.text.chars().filter(|&ch| ch == '\t').count();
let run_id = tree.next_id();
let run_node = RenderNode::new(
run_id,
RenderNodeType::TextRun(TextRunNode {
text,
style: text_style,
char_shape_id: None,
para_shape_id: None,
section_index: Some(marker_section),
para_index: Some(marker_para),
char_start: Some(char_offset + skipped),
cell_context: None,
is_para_end: false,
is_line_break_end: false,
rotation: 0.0,
is_vertical: false,
char_overlap: run.char_overlap.clone(),
border_fill_id: 0,
baseline,
field_marker: FieldMarkerType::None,
layout_positions: None,
display_text: None,
}),
BoundingBox::new(x, y, width, line_height),
);
line_node.children.push(run_node);
x += width;
char_offset += run.text.chars().count();
}
parent.children.push(line_node);
let is_last_line = offset + 1 >= line_end - line_start;
if is_last_selected_line && is_last_line {
y += line_height;
} else {
let line_spacing_px = corrected_line_spacing;
y += line_height + line_spacing_px;
}
}
if composed.lines.is_empty() {
let default_height = hwpunit_to_px(400, self.dpi);
let line_id = tree.next_id();
let line_node = RenderNode::new(
line_id,
RenderNodeType::TextLine(TextLineNode::new(default_height, default_height * 0.8)),
BoundingBox::new(area.x, y, area.width, default_height),
);
parent.children.push(line_node);
y += default_height;
}
y
}
pub(crate) fn add_footnote_superscripts(
&self,
tree: &mut PageLayoutContext,
parent: &mut RenderNode,
para: &Paragraph,
_styles: &ResolvedStyleSet,
) {
let has_inline_markers = parent.children.iter().any(|line| {
line.children
.iter()
.any(|n| matches!(n.node_type, RenderNodeType::FootnoteMarker(_)))
});
if has_inline_markers {
return;
}
let ctrl_positions = para.control_text_positions();
let mut footnotes: Vec<(String, usize)> = Vec::new();
for (ci, ctrl) in para.controls.iter().enumerate() {
let marker_text = match ctrl {
Control::Footnote(note) => Some(
super::paragraph_layout::note_marker_text_from_control(Some(ctrl), note.number),
),
Control::Endnote(note) => Some(
super::paragraph_layout::note_marker_text_from_control(Some(ctrl), note.number),
),
_ => None,
};
if let Some(text) = marker_text {
let pos = ctrl_positions.get(ci).copied().unwrap_or(usize::MAX);
footnotes.push((text, pos));
}
}
if footnotes.is_empty() {
return;
}
for (_fn_idx, (number_text, char_pos)) in footnotes.iter().enumerate() {
let mut target_line_idx: Option<usize> = None;
let mut insert_x = 0.0;
let mut line_height = 18.0;
let mut line_y = 0.0;
let mut base_font_size = 12.0_f64;
let mut base_font_family = "sans-serif".to_string();
if *char_pos < usize::MAX {
'outer: for (li, line_node) in parent.children.iter().enumerate() {
if !matches!(line_node.node_type, RenderNodeType::TextLine(_)) {
continue;
}
let mut line_min_cs = usize::MAX;
let mut line_max_end = 0usize;
for run_node in &line_node.children {
if let RenderNodeType::TextRun(ref run) = run_node.node_type {
if let Some(cs) = run.char_start {
line_min_cs = line_min_cs.min(cs);
line_max_end = line_max_end.max(cs + run.text.chars().count());
}
}
}
if *char_pos > line_max_end || line_min_cs == usize::MAX {
continue;
}
for run_node in &line_node.children {
if let RenderNodeType::TextRun(ref run) = run_node.node_type {
if let Some(cs) = run.char_start {
let run_len = run.text.chars().count();
let run_end = cs + run_len;
if *char_pos >= cs && *char_pos <= run_end {
let chars_before = char_pos - cs;
let partial_text: String =
run.text.chars().take(chars_before).collect();
let partial_width =
estimate_text_width(&partial_text, &run.style);
insert_x = run_node.bbox.x + partial_width;
line_height = line_node.bbox.height;
line_y = line_node.bbox.y;
base_font_size = run.style.font_size;
base_font_family = run.style.font_family.clone();
target_line_idx = Some(li);
break 'outer;
}
}
}
}
}
}
if target_line_idx.is_none() {
if let Some(li) = parent
.children
.iter()
.rposition(|n| matches!(n.node_type, RenderNodeType::TextLine(_)))
{
let line = &parent.children[li];
insert_x = line
.children
.last()
.map(|c| c.bbox.x + c.bbox.width)
.unwrap_or(line.bbox.x);
line_height = line.bbox.height;
line_y = line.bbox.y;
if let Some(last_run) = line.children.last() {
if let RenderNodeType::TextRun(ref run) = last_run.node_type {
base_font_size = run.style.font_size;
base_font_family = run.style.font_family.clone();
}
}
target_line_idx = Some(li);
}
}
if let Some(line_idx) = target_line_idx {
let sup_font_size = (base_font_size * 0.6).max(7.0);
let sup_y_offset = line_height * 0.35;
let style = TextStyle {
font_size: sup_font_size,
font_family: base_font_family,
..Default::default()
};
let width = estimate_text_width(&number_text, &style);
let run_id = tree.next_id();
let run_node = RenderNode::new(
run_id,
RenderNodeType::TextRun(TextRunNode {
text: number_text.clone(),
style,
char_shape_id: None,
para_shape_id: None,
section_index: None,
para_index: None,
char_start: None,
cell_context: None,
is_para_end: false,
is_line_break_end: false,
rotation: 0.0,
is_vertical: false,
char_overlap: None,
border_fill_id: 0,
baseline: line_height,
field_marker: FieldMarkerType::None,
layout_positions: None,
display_text: None,
}),
BoundingBox::new(insert_x, line_y - sup_y_offset, width, line_height),
);
let line_mut = &mut parent.children[line_idx];
line_mut.children.push(run_node);
}
}
}
}
fn get_footnote_paragraphs<'a>(
fn_ref: &FootnoteRef,
paragraphs: &'a [Paragraph],
) -> &'a [Paragraph] {
match &fn_ref.source {
FootnoteSource::Body {
para_index,
control_index,
} => {
if let Some(para) = paragraphs.get(*para_index) {
if let Some(Control::Footnote(footnote)) = para.controls.get(*control_index) {
return &footnote.paragraphs;
}
}
&[]
}
FootnoteSource::TableCell {
para_index,
table_control_index,
cell_index,
cell_para_index,
cell_control_index,
} => {
if let Some(para) = paragraphs.get(*para_index) {
if let Some(Control::Table(table)) = para.controls.get(*table_control_index) {
if let Some(cell) = table.cells.get(*cell_index) {
if let Some(cp) = cell.paragraphs.get(*cell_para_index) {
if let Some(Control::Footnote(footnote)) =
cp.controls.get(*cell_control_index)
{
return &footnote.paragraphs;
}
}
}
}
}
&[]
}
FootnoteSource::NestedTableCell {
para_index,
table_control_index,
cell_path,
} => {
let Some(Control::Table(table)) = paragraphs
.get(*para_index)
.and_then(|para| para.controls.get(*table_control_index))
else {
return &[];
};
let mut table = table.as_ref();
for (index, entry) in cell_path.iter().enumerate() {
let Some(control) = table
.cells
.get(entry.cell_index)
.and_then(|cell| cell.paragraphs.get(entry.cell_para_index))
.and_then(|para| para.controls.get(entry.control_index))
else {
return &[];
};
if index + 1 == cell_path.len() {
return match control {
Control::Footnote(note) => ¬e.paragraphs,
_ => &[],
};
}
let Control::Table(child) = control else {
return &[];
};
table = child;
}
&[]
}
FootnoteSource::ShapeTextBox {
para_index,
shape_control_index,
tb_para_index,
tb_control_index,
} => {
if let Some(para) = paragraphs.get(*para_index) {
if let Some(Control::Shape(shape_obj)) = para.controls.get(*shape_control_index) {
if let Some(text_box) = shape_obj.drawing().and_then(|d| d.text_box.as_ref()) {
if let Some(tp) = text_box.paragraphs.get(*tb_para_index) {
if let Some(Control::Footnote(footnote)) =
tp.controls.get(*tb_control_index)
{
return &footnote.paragraphs;
}
}
}
}
}
&[]
}
}
}
fn format_footnote_number(
number: u16,
format: &NumberFormat,
prefix: char,
suffix: char,
user_symbol: char,
) -> String {
let code = FootnoteShape::number_format_attr_code(*format) as u8;
let num_str = crate::renderer::note_marker::number_text(number, code, user_symbol);
let prefix_str = if prefix != '\0' {
prefix.to_string()
} else {
String::new()
};
let suffix_str = if suffix != '\0' {
suffix.to_string()
} else {
")".to_string()
};
format!("{}{}{} ", prefix_str, num_str, suffix_str)
}