use crate::model::control::Control;
use crate::model::paragraph::CellGrid;
pub(crate) fn pairs_in_cell(ch: char) -> bool {
ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.' || ch == ','
}
fn in_latin_word(ch: char) -> bool {
ch.is_ascii_graphic()
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct LinePlacement {
pub cell: Vec<usize>,
pub offset: Vec<f64>,
pub cells: usize,
}
pub(crate) fn place_line(
chars: &[char],
advances: &[f64],
digit_advances: &[f64],
first_cell: usize,
cols: usize,
cell: f64,
) -> LinePlacement {
let mut placement = LinePlacement {
cell: vec![0; chars.len()],
offset: vec![0.0; chars.len()],
cells: first_cell,
};
let advance = |i: usize| advances.get(i).copied().unwrap_or(0.0);
let mut i = 0;
while i < chars.len() {
let k = placement.cells;
if k > cols {
let mut x = 0.0;
for j in i..chars.len() {
placement.cell[j] = k;
placement.offset[j] = x;
x += advance(j);
}
placement.cells = k + 1;
break;
}
if pairs_in_cell(chars[i]) && chars.get(i + 1).copied().is_some_and(pairs_in_cell) {
let start = (cell - advance(i) - advance(i + 1)) / 2.0;
placement.cell[i] = k;
placement.cell[i + 1] = k;
placement.offset[i] = start;
placement.offset[i + 1] = start + advance(i);
i += 2;
} else {
placement.cell[i] = k;
placement.offset[i] = if matches!(chars[i], '.' | ',') {
(cell - 2.0 * digit_advances.get(i).copied().unwrap_or(0.0)) / 2.0
} else {
(cell - advance(i)) / 2.0
};
i += 1;
}
placement.cells = k + 1;
}
placement
}
fn word_cells(chars: &[char]) -> usize {
let mut cells = 0;
let mut i = 0;
while i < chars.len() {
i += if pairs_in_cell(chars[i]) && chars.get(i + 1).copied().is_some_and(pairs_in_cell) {
2
} else {
1
};
cells += 1;
}
cells
}
pub(crate) fn line_starts(
chars: &[char],
natural: &[i32],
cols: usize,
cell: i32,
first_cells: usize,
) -> Vec<usize> {
let cols = cols.max(1);
let line_width = i64::from(cell) * cols as i64;
let mut starts = vec![0];
let mut line_start = 0;
let mut k = first_cells;
let mut i = 0;
let mut break_before = |i: usize, line_start: &mut usize, k: &mut usize| {
starts.push(i);
*line_start = i;
*k = 0;
};
while i < chars.len() {
let ch = chars[i];
if ch == '\n' {
i += 1;
break_before(i, &mut line_start, &mut k);
continue;
}
if ch == ' ' || ch == '\t' {
k += 1;
i += 1;
continue;
}
if in_latin_word(ch) {
let end = (i..chars.len())
.find(|&j| !in_latin_word(chars[j]))
.unwrap_or(chars.len());
let width: i64 = (i..end)
.map(|j| i64::from(natural.get(j).copied().unwrap_or(cell)))
.sum();
let fits = i64::from(cell) * k as i64 + width <= line_width;
if !fits
&& i > line_start
&& k > 0
&& !crate::renderer::composer::is_line_start_forbidden(ch)
{
break_before(i, &mut line_start, &mut k);
}
k += word_cells(&chars[i..end]);
i = end;
continue;
}
if k >= cols && i > line_start && !crate::renderer::composer::is_line_start_forbidden(ch) {
break_before(i, &mut line_start, &mut k);
}
k += 1;
i += 1;
}
starts
}
pub(crate) fn indent_cells(indent_hu: i32, grid: CellGrid) -> usize {
if indent_hu <= 0 || grid.cell <= 0 {
0
} else {
((indent_hu + grid.cell - 1) / grid.cell) as usize
}
}
pub(crate) fn line_pitch(height: i32, grid: CellGrid) -> i32 {
let steps = if height <= 0 {
1
} else {
height.saturating_add(grid.line - 1) / grid.line
};
steps.max(1).saturating_mul(grid.line)
}
pub(crate) fn place_line_runs(
line: &mut crate::renderer::render_tree::RenderNode,
grid: CellGrid,
origin: f64,
width: f64,
first_cells: usize,
dpi: f64,
next_id: &mut dyn FnMut() -> crate::renderer::render_tree::NodeId,
) {
use crate::renderer::layout::{compute_char_positions, estimate_text_width};
use crate::renderer::render_tree::RenderNodeType;
let cell = crate::renderer::hwpunit_to_px(grid.cell, dpi);
if cell <= 0.0 {
return;
}
if line.children.iter().any(|child| match &child.node_type {
RenderNodeType::TextRun(run) => run.display_text.is_some() || run.char_overlap.is_some(),
_ => false,
}) {
return;
}
let mut chars = Vec::new();
let mut advances = Vec::new();
let mut digits = Vec::new();
for child in &mut line.children {
let RenderNodeType::TextRun(run) = &mut child.node_type else {
continue;
};
run.style.extra_word_spacing = 0.0;
run.style.extra_char_spacing = 0.0;
run.style.extra_dash_advance = 0.0;
let positions = compute_char_positions(&run.text, &run.style);
let digit = estimate_text_width("0", &run.style);
for (i, ch) in run.text.chars().enumerate() {
chars.push(ch);
advances.push(positions.get(i + 1).copied().unwrap_or(0.0) - positions[i]);
digits.push(digit);
}
}
let cols = (width / cell + 1e-6).floor().max(1.0) as usize;
let placement = place_line(&chars, &advances, &digits, first_cells, cols, cell);
let mut next = 0;
for mut child in std::mem::take(&mut line.children) {
let RenderNodeType::TextRun(run) = &mut child.node_type else {
line.children.push(child);
continue;
};
let text: Vec<char> = run.text.chars().collect();
if text.is_empty() {
child.bbox.x = origin + placement.cells as f64 * cell;
line.children.push(child);
continue;
}
let splittable = matches!(
run.field_marker,
crate::renderer::render_tree::FieldMarkerType::None
);
let mut start = 0;
while start < text.len() {
let mut end = start + 1;
while end < text.len()
&& (!splittable || placement.cell[next + end] == placement.cell[next + start])
{
end += 1;
}
let x = |i: usize| {
origin + placement.cell[next + i] as f64 * cell + placement.offset[next + i]
};
let left = x(start);
let mut positions = Vec::with_capacity(end - start + 1);
let mut previous = 0.0f64;
for i in start..end {
previous = previous.max(x(i) - left);
positions.push(previous);
}
positions.push(previous.max(x(end - 1) - left + advances[next + end - 1]));
let mut piece = child.clone();
if start > 0 {
piece.id = next_id();
}
if let RenderNodeType::TextRun(part) = &mut piece.node_type {
if start > 0 || end < text.len() {
part.text = text[start..end].iter().collect();
part.char_start = part.char_start.map(|first| first + start);
}
if end < text.len() {
part.is_para_end = false;
part.is_line_break_end = false;
}
}
piece.bbox.x = left;
piece.bbox.width = positions[end - start];
if let RenderNodeType::TextRun(part) = &mut piece.node_type {
part.layout_positions = Some(positions);
}
line.children.push(piece);
start = end;
}
next += text.len();
}
}
pub(crate) fn paragraph_takes_grid(
para: &crate::model::paragraph::Paragraph,
para_shapes: &[crate::model::style::ParaShape],
) -> bool {
!para.line_segs.is_empty() && shape_takes_grid(para, para_shapes)
}
pub(crate) fn shape_takes_grid(
para: &crate::model::paragraph::Paragraph,
para_shapes: &[crate::model::style::ParaShape],
) -> bool {
para_shapes
.get(para.para_shape_id as usize)
.is_some_and(|shape| shape.attr1 & (1 << 8) != 0)
&& para.controls.iter().all(|control| {
matches!(control, Control::Header(_) | Control::Footer(_))
|| crate::renderer::composer::control_is_width_neutral_marker(control)
})
}
pub(crate) fn project_section_rows(
paragraphs: &mut [crate::model::paragraph::Paragraph],
para_shapes: &[crate::model::style::ParaShape],
grid: CellGrid,
) -> Vec<usize> {
let mut changed = Vec::new();
let mut next_y: Option<i32> = None;
let mut previous_first: Option<i32> = None;
for (index, para) in paragraphs.iter_mut().enumerate() {
let Some(first) = para.line_segs.first().map(|line| line.vertical_pos) else {
continue;
};
if !paragraph_takes_grid(para, para_shapes) {
next_y = para.line_segs.last().map(|line| {
line.vertical_pos
.saturating_add(line.line_height)
.saturating_add(line.line_spacing)
});
previous_first = Some(first);
continue;
}
let mut y = match (next_y, previous_first) {
(_, Some(previous)) if first < previous => first,
(Some(end), _) => end,
_ => first,
};
for line in &mut para.line_segs {
let pitch = line_pitch(line.line_height, grid);
line.baseline_distance = line
.baseline_distance
.saturating_add((pitch - line.line_height) / 2);
line.line_height = pitch;
line.text_height = pitch;
line.line_spacing = 0;
line.vertical_pos = y;
y = y.saturating_add(pitch);
}
para.layout_cell_grid = Some(grid);
next_y = Some(y);
previous_first = Some(first);
changed.push(index);
}
changed
}
pub(crate) fn rebreak_paragraph(
para: &mut crate::model::paragraph::Paragraph,
grid: CellGrid,
width_hu: i32,
indent_hu: i32,
styles: &crate::renderer::style_resolver::ResolvedStyleSet,
dpi: f64,
) {
use crate::model::paragraph::LineSeg;
let Some(template) = para.line_segs.first().cloned() else {
return;
};
let chars: Vec<char> = para.text.chars().collect();
let natural: Vec<i32> = chars
.iter()
.enumerate()
.map(|(i, &ch)| {
if !ch.is_ascii_graphic() {
return grid.cell;
}
let style = crate::renderer::layout::resolved_to_text_style(
styles,
para.char_shape_id_at(i).unwrap_or(0),
1,
);
let mut buf = [0u8; 4];
let px = crate::renderer::layout::estimate_text_width(ch.encode_utf8(&mut buf), &style);
crate::renderer::px_to_hwpunit(px, dpi)
})
.collect();
let cols = (width_hu / grid.cell.max(1)).max(1) as usize;
let starts = line_starts(
&chars,
&natural,
cols,
grid.cell,
indent_cells(indent_hu, grid),
);
let follow_tag = para
.line_segs
.get(1)
.map_or(template.tag & !LineSeg::TAG_INDENTATION, |line| line.tag);
let text_end = para
.char_offsets
.last()
.zip(chars.last())
.map_or(0, |(offset, &ch)| {
offset + crate::model::paragraph::Paragraph::char_stream_len(ch)
});
let mut y = template.vertical_pos;
let mut lines = Vec::with_capacity(starts.len());
for (n, &start) in starts.iter().enumerate() {
let end = starts.get(n + 1).copied().unwrap_or(chars.len());
let height = (start..end)
.filter_map(|i| {
let id = para.char_shape_id_at(i)?;
styles.char_styles.get(id as usize)
})
.map(|style| crate::renderer::px_to_hwpunit(style.font_size, dpi))
.max()
.filter(|height| *height > 0)
.unwrap_or(template.line_height);
let pitch = line_pitch(height, grid);
lines.push(LineSeg {
text_start: if n == 0 {
template.text_start
} else {
para.char_offsets.get(start).copied().unwrap_or(text_end)
},
vertical_pos: y,
line_height: height,
text_height: height,
baseline_distance: (f64::from(height) * 0.85).round() as i32,
line_spacing: pitch - height,
tag: if n == 0 { template.tag } else { follow_tag },
..template.clone()
});
y = y.saturating_add(pitch);
}
para.line_segs = lines;
para.layout_space_metrics.clear();
}
pub(crate) fn fit_body_paragraph(
section: &mut crate::model::document::Section,
para_shapes: &[crate::model::style::ParaShape],
para_idx: usize,
column_width_px: f64,
styles: &crate::renderer::style_resolver::ResolvedStyleSet,
dpi: f64,
) {
let Some(grid) = section.section_def.cell_grid() else {
return;
};
if let Some(para) = section.paragraphs.get_mut(para_idx) {
if let (true, Some(style)) = (
paragraph_takes_grid(para, para_shapes),
styles.para_styles.get(para.para_shape_id as usize),
) {
let width = crate::renderer::px_to_hwpunit(
column_width_px - style.margin_left - style.margin_right,
dpi,
);
let indent = crate::renderer::px_to_hwpunit(style.indent, dpi);
rebreak_paragraph(para, grid, width, indent, styles, dpi);
}
}
fit_section_spacing(&mut section.paragraphs, para_shapes, grid);
}
pub(crate) fn fit_section_spacing(
paragraphs: &mut [crate::model::paragraph::Paragraph],
para_shapes: &[crate::model::style::ParaShape],
grid: CellGrid,
) -> bool {
let mut changed = false;
for para in paragraphs.iter_mut() {
if !paragraph_takes_grid(para, para_shapes) {
continue;
}
for line in &mut para.line_segs {
let spacing = line_pitch(line.line_height, grid) - line.line_height;
if line.line_spacing != spacing {
line.line_spacing = spacing;
changed = true;
}
}
}
changed
}