use super::picture_anchor_projection::{self, FramePurpose};
use super::supplemental_clusters::ParagraphMetricScope;
use super::{char_lang_slot, find_active_char_shape, is_lang_neutral, ComposedParagraph};
use crate::model::control::{Control, CTRL_CHAR_CODE_UNITS};
use crate::model::paragraph::{CharShapeRef, ColumnBreakType, LineSeg, Paragraph, SpaceMetric};
use crate::model::style::{Alignment, HeadType, LineSpacingType};
use crate::renderer::equation_tac_flow::indent_leaves_line_room_hwp;
use crate::renderer::layout::{
estimate_text_width, estimate_text_width_unrounded, glyph_letter_spacing_advance,
hancom_regenerated_space_width, is_cjk_char, kopub_space_advance_em, resolved_letter_spacing,
};
use crate::renderer::layout_frame::{FrameRowMetrics, LayoutFrame, ParagraphBox, RowSegment};
use crate::renderer::style_resolver::storage::{Storage, Unbounded};
use crate::renderer::style_resolver::{
detect_lang_category, is_latin_slot_symbol, ResolvedParaStyle, ResolvedStyleSet,
};
use crate::renderer::{hwpunit_to_px, px_to_hwpunit};
use std::ops::Range;
mod inline_frame_input;
mod list_marker_metrics;
mod stored_external_geometry;
use stored_external_geometry::stored_rows_require_external_geometry;
struct PreparedParagraphKerning {
context: std::sync::Arc<crate::renderer::kerning::KerningMeasurementContext>,
scalar_styles: Vec<crate::renderer::kerning::KerningParagraphScalarStyle>,
hard_boundaries: Vec<bool>,
measurement: std::sync::Arc<crate::renderer::kerning::KerningParagraphMeasurement>,
}
struct PreparedParagraphProjection {
base_positions: Vec<f64>,
kerning_scalar_styles: Vec<crate::renderer::kerning::KerningParagraphScalarStyle>,
shaping_scalar_styles:
Vec<crate::renderer::shaping_paragraph::HorizontalShapingParagraphScalarStyle>,
hard_boundaries: Vec<bool>,
}
#[derive(Debug, Clone)]
pub(crate) struct PictureBandLayout {
pub(crate) paragraph_range: Range<usize>,
pub(crate) line_segs: Vec<Vec<LineSeg>>,
pub(crate) space_metrics: Vec<Vec<(u32, SpaceMetric)>>,
pub(crate) preserved_stored: Vec<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StoredRowResolution {
Stored,
Reflowed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StoredRowMissPolicy {
Reflow,
UnmodelledUnlessStale,
}
#[derive(Debug, Clone)]
pub(crate) enum BreakToken {
DiscretionaryHyphen {
idx: usize,
width: f64,
max_font_size: f64,
},
Text {
start_idx: usize,
end_idx: usize,
base_width: f64,
width: f64,
max_font_size: f64,
base_char_widths: Vec<f64>,
char_widths: Vec<f64>,
},
Space {
idx: usize,
width: f64,
condense_base: f64,
max_font_size: f64,
inline_width: f64,
},
Tab {
idx: usize,
max_font_size: f64,
auto_left_target: Option<f64>,
},
LineBreak { idx: usize },
}
#[derive(Debug, Clone, Copy)]
struct FlowInlineControl {
char_position: usize,
utf16_position: u32,
width_hwp: i32,
height_hwp: i32,
baseline_distance_hwp: Option<i32>,
spacing_height_hwp: Option<i32>,
}
#[derive(Debug, Clone, PartialEq)]
struct LineBreakResult {
start_idx: usize,
end_idx: usize, max_font_size: f64,
has_line_break: bool, }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FillTermination {
IntervalFull,
ForcedBreak,
ParagraphEnd,
}
#[derive(Debug, Clone, PartialEq)]
struct FilledInterval {
line: LineBreakResult,
termination: FillTermination,
}
pub(crate) fn is_line_start_forbidden(ch: char) -> bool {
matches!(
ch,
')' | ']'
| '}'
| ','
| '.'
| '!'
| '?'
| ';'
| ':'
| '\''
| '"'
| '\u{3001}'
| '\u{3002}'
| '\u{2026}'
| '\u{2024}'
| '\u{00B7}'
| '\u{2027}'
| '\u{2015}'
| '\u{30FC}'
| '\u{300B}'
| '\u{300D}'
| '\u{300F}'
| '\u{3011}'
| '\u{FF09}'
| '\u{FF5D}'
| '\u{3015}'
| '\u{3009}'
| '\u{FF1E}'
| '\u{226B}'
| '\u{FF3D}'
| '\u{FE5E}'
| '\u{301E}'
| '\u{2019}'
| '\u{201D}'
| '\u{FF0C}'
| '\u{FF0E}'
| '\u{FF01}'
| '\u{FF1F}'
| '\u{FF1B}'
| '\u{FF1A}'
| '%'
| '\u{2030}'
| '\u{2103}'
| '\u{00B0}'
| '\u{FF05}'
)
}
fn break_before_text_token(
text_chars: &[char],
start_idx: usize,
line_start_idx: usize,
korean_break_unit: u8,
) -> bool {
if start_idx <= line_start_idx || start_idx >= text_chars.len() {
return false;
}
let previous = text_chars[start_idx - 1];
if text_chars[start_idx] == '\u{FFFC}'
&& !previous.is_whitespace()
&& !is_line_end_forbidden(previous)
&& !matches!(previous, '\u{2060}' | '\u{FEFF}')
{
return true;
}
if matches!(previous, '\u{2024}' | '\u{2219}')
&& !is_line_start_forbidden(text_chars[start_idx])
{
return true;
}
let closing_apostrophe =
previous == '\'' && start_idx >= 2 && text_chars[start_idx - 2].is_alphanumeric();
let paired_angle_open = previous == '<'
&& text_chars
.get(start_idx)
.is_some_and(|c| !c.is_whitespace())
&& text_chars[start_idx..]
.iter()
.take_while(|c| !matches!(**c, '\n' | '\r' | '<'))
.any(|c| *c == '>');
korean_break_unit == 1
&& start_idx > line_start_idx
&& text_chars.get(start_idx).is_some_and(|c| is_hangul(*c))
&& text_chars.get(start_idx - 1).is_some_and(|prev| {
!prev.is_whitespace()
&& !paired_angle_open
&& (!is_line_end_forbidden(*prev) || closing_apostrophe)
})
}
fn can_break_after_text_token(ch: char, korean_break_unit: u8) -> bool {
if is_hangul(ch) || ch.is_ascii_digit() {
korean_break_unit == 1
} else {
is_cjk_ideograph(ch) || matches!(ch, '\u{3300}'..='\u{33FF}' | '\u{2024}' | '\u{2027}')
}
}
pub(crate) fn is_line_end_forbidden(ch: char) -> bool {
matches!(
ch,
'(' | '['
| '{'
| '\''
| '\u{300A}'
| '\u{300C}'
| '\u{300E}'
| '\u{3010}'
| '\u{FF08}'
| '\u{FF5B}'
| '\u{3014}'
| '\u{3008}'
| '\u{FF1C}'
| '\u{226A}'
| '\u{FF3B}'
| '\u{301D}'
| '\u{2018}'
| '\u{201C}'
| '$'
| '\u{20A9}'
| '\u{00A3}'
| '\u{20AC}'
| '\u{00A5}'
| '\u{FF04}'
| '\u{FFE5}'
)
}
fn is_hangul(ch: char) -> bool {
('\u{AC00}'..='\u{D7A3}').contains(&ch) || ('\u{1100}'..='\u{11FF}').contains(&ch) || ('\u{3130}'..='\u{318F}').contains(&ch) || ('\u{A960}'..='\u{A97F}').contains(&ch) || ('\u{D7B0}'..='\u{D7FF}').contains(&ch) }
fn is_latin(ch: char) -> bool {
detect_lang_category(ch) == 1 && !is_latin_slot_symbol(ch)
}
fn stays_in_latin_word(ch: char) -> bool {
is_lang_neutral(ch) || matches!(ch, '\u{00A1}'..='\u{00BF}')
}
fn numeric_run_before_non_latin_closer(chars: &[char], start: usize) -> Option<usize> {
let end = start
+ chars[start..]
.iter()
.take_while(|ch| ch.is_ascii_digit())
.count();
chars
.get(end)
.filter(|ch| is_line_start_forbidden(**ch) && !is_latin(**ch) && !stays_in_latin_word(**ch))
.map(|_| end)
}
fn is_cjk_ideograph(ch: char) -> bool {
let lang = detect_lang_category(ch);
lang == 2 || lang == 3 }
pub(crate) fn tokenize_paragraph(
text_chars: &[char],
char_offsets: &[u32],
char_shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
english_break_unit: u8,
korean_break_unit: u8,
) -> Vec<BreakToken> {
tokenize_paragraph_with_regenerated_space_metric(
text_chars,
char_offsets,
char_shapes,
styles,
english_break_unit,
korean_break_unit,
SpaceMetric::Stored,
&[],
false,
&[],
)
}
impl SpaceMetric {
pub(crate) fn apply_to_style(self, style: &mut crate::renderer::TextStyle) {
match self {
Self::Stored => {}
Self::HancomRegenerated => {
if hancom_regenerated_space_width(style).is_some() {
style.layout_half_space = true;
}
}
Self::HalfCell => {
style.layout_half_space = true;
}
Self::KoPubJustified => {
if let Some(em) = kopub_space_advance_em(style) {
style.font_space_em = Some(em);
}
}
}
}
fn space_advance(self, style: &crate::renderer::TextStyle) -> f64 {
let mut selected = style.clone();
self.apply_to_style(&mut selected);
estimate_text_width_unrounded(" ", &selected)
}
}
fn token_line_font_size(styles: &ResolvedStyleSet, style_id: u32) -> f64 {
styles
.char_styles
.get(style_id as usize)
.map(|s| s.font_size)
.filter(|size| *size > 0.0)
.unwrap_or(12.0)
}
pub(crate) fn text_word_ranges(para: &Paragraph, styles: &ResolvedStyleSet) -> Vec<Range<usize>> {
match text_word_ranges_with_storage(para, styles, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn text_word_ranges_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<Vec<Range<usize>>, S::Error> {
let chars: Vec<_> = storage.collect(para.text.chars())?;
let style = styles.para_styles.get(para.para_shape_id as usize);
storage.collect(
try_tokenize_paragraph_with_regenerated_space_metric(
&chars,
¶.char_offsets,
¶.char_shapes,
styles,
style.map_or(0, |s| s.english_break_unit),
style.map_or(0, |s| s.korean_break_unit),
SpaceMetric::Stored,
&[],
para.control_mask & (1 << 0x18) != 0,
¶.literal_figure_spaces,
storage,
)?
.into_iter()
.filter_map(|token| match token {
BreakToken::Text {
start_idx, end_idx, ..
} => Some(start_idx..end_idx),
_ => None,
}),
)
}
fn tokenize_paragraph_with_regenerated_space_metric(
text_chars: &[char],
char_offsets: &[u32],
char_shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
english_break_unit: u8,
korean_break_unit: u8,
space_metric: SpaceMetric,
inline_controls: &[FlowInlineControl],
soft_hyphen_control: bool,
literal_figure_spaces: &[usize],
) -> Vec<BreakToken> {
match try_tokenize_paragraph_with_regenerated_space_metric(
text_chars,
char_offsets,
char_shapes,
styles,
english_break_unit,
korean_break_unit,
space_metric,
inline_controls,
soft_hyphen_control,
literal_figure_spaces,
&crate::renderer::style_resolver::storage::Unbounded,
) {
Ok(tokens) => tokens,
Err(never) => match never {},
}
}
fn try_tokenize_paragraph_with_regenerated_space_metric<
S: crate::renderer::style_resolver::storage::Storage,
>(
text_chars: &[char],
char_offsets: &[u32],
char_shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
english_break_unit: u8,
korean_break_unit: u8,
space_metric: SpaceMetric,
inline_controls: &[FlowInlineControl],
soft_hyphen_control: bool,
literal_figure_spaces: &[usize],
storage: &S,
) -> Result<Vec<BreakToken>, S::Error> {
let text_len = text_chars.len();
if text_len == 0 {
return Ok(Vec::new());
}
let mut tokens = Vec::new();
let mut i = 0;
let metric_scope = ParagraphMetricScope::try_new(text_chars, styles, storage)?
.with_space_metric(space_metric)
.with_literal_figure_spaces(literal_figure_spaces);
let mut current_lang: usize = 0;
let mut numeric_closer_end = 0;
while i < text_len {
storage.reserve(&mut tokens, 1)?;
let ch = text_chars[i];
if soft_hyphen_control && ch == '\u{00AD}' {
let position = char_offsets.get(i).copied().unwrap_or(i as u32);
let shape = find_active_char_shape(char_shapes, position);
let style = metric_scope.try_style(styles, shape, current_lang, i, storage)?;
storage.push(
&mut tokens,
BreakToken::DiscretionaryHyphen {
idx: i,
width: estimate_text_width_unrounded("-", &style),
max_font_size: token_line_font_size(styles, shape),
},
)?;
i += 1;
continue;
}
if ch == '\n' {
storage.push(&mut tokens, BreakToken::LineBreak { idx: i })?;
i += 1;
continue;
}
if ch == '\t' {
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
let font_size = token_line_font_size(styles, style_id);
storage.push(
&mut tokens,
BreakToken::Tab {
idx: i,
max_font_size: font_size,
auto_left_target: None,
},
)?;
i += 1;
continue;
}
if ch == '\u{FFFC}'
&& inline_controls
.iter()
.any(|control| control.char_position == i)
{
let width = inline_width_px_at(inline_controls, i, styles);
let style_id = find_active_char_shape(
char_shapes,
char_offsets.get(i).copied().unwrap_or(i as u32),
);
storage.push(
&mut tokens,
BreakToken::Text {
start_idx: i,
end_idx: i + 1,
base_width: width,
width,
max_font_size: token_line_font_size(styles, style_id),
base_char_widths: storage.collect([width])?,
char_widths: storage.collect([width])?,
},
)?;
i += 1;
continue;
}
if ch == ' ' {
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
let font_size = token_line_font_size(styles, style_id);
let inline_width = inline_width_px_at(inline_controls, i, styles);
let unspaced = crate::renderer::TextStyle {
letter_spacing: 0.0,
..ts.clone()
};
storage.push(
&mut tokens,
BreakToken::Space {
idx: i,
width: space_metric.space_advance(&ts) + inline_width,
condense_base: space_metric.space_advance(&unspaced),
max_font_size: font_size,
inline_width,
},
)?;
i += 1;
continue;
}
if korean_break_unit == 1 && ch.is_ascii_digit() && i >= numeric_closer_end {
numeric_closer_end = numeric_run_before_non_latin_closer(text_chars, i).unwrap_or(i);
}
let numeric_closer =
korean_break_unit == 1 && ch.is_ascii_digit() && i < numeric_closer_end;
if is_hangul(ch) || is_cjk_ideograph(ch) || numeric_closer {
if korean_break_unit == 0 && is_hangul(ch) {
let start = i;
let mut max_fs = 0.0f64;
let mut token_lang = current_lang;
while i < text_len {
let c = text_chars[i];
if soft_hyphen_control && c == '\u{00AD}' {
break;
}
if c == ' ' || c == '\n' || c == '\t' || c == '\u{FFFC}' {
break;
}
if !is_hangul(c) && is_latin(c) {
break;
}
if is_cjk_ideograph(c) {
break;
}
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let lang = if is_lang_neutral(c) {
token_lang
} else {
let detected = detect_lang_category(c);
token_lang = detected;
current_lang = detected;
detected
};
let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
if fs > max_fs {
max_fs = fs;
}
i += 1;
}
while i < text_len
&& is_line_start_forbidden(text_chars[i])
&& text_chars[i] != '\n'
&& text_chars[i] != '\t'
{
let c = text_chars[i];
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let lang = if is_lang_neutral(c) {
current_lang
} else {
let detected = detect_lang_category(c);
current_lang = detected;
detected
};
let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
if fs > max_fs {
max_fs = fs;
}
i += 1;
}
if i > start {
let (width, char_widths) = try_measure_token_chars(
&metric_scope,
&text_chars[start..i],
start,
char_offsets,
char_shapes,
styles,
current_lang,
inline_controls,
true,
storage,
)?;
storage.push(
&mut tokens,
BreakToken::Text {
start_idx: start,
end_idx: i,
base_width: width,
width,
max_font_size: max_fs,
base_char_widths: storage.copy_slice(&char_widths)?,
char_widths,
},
)?;
}
continue;
} else {
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
current_lang = detect_lang_category(ch);
let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
let cluster_end = hangul_jamo_cluster_end(text_chars, i);
let mut single = [0u8; 4];
let display = metric_display(&text_chars[i..cluster_end], &mut single, storage)?;
let mut w = estimate_text_width_unrounded(&display, &ts)
+ (i..cluster_end)
.map(|idx| inline_width_px_at(inline_controls, idx, styles))
.sum::<f64>();
let start = i;
i = cluster_end;
while i < text_len
&& is_line_start_forbidden(text_chars[i])
&& text_chars[i] != '\n'
&& text_chars[i] != '\t'
{
let follow_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let follow_style = find_active_char_shape(char_shapes, follow_pos);
let follow_lang = if is_lang_neutral(text_chars[i]) {
current_lang
} else {
detect_lang_category(text_chars[i])
};
let follow_ts =
metric_scope.try_style(styles, follow_style, follow_lang, i, storage)?;
w += reflow_scalar_width(text_chars[i], &follow_ts)
+ inline_width_px_at(inline_controls, i, styles);
i += 1;
}
storage.push(
&mut tokens,
BreakToken::Text {
start_idx: start,
end_idx: i,
base_width: w,
width: w,
max_font_size: fs,
base_char_widths: vec![],
char_widths: vec![],
},
)?;
continue;
}
}
if is_latin(ch) {
if english_break_unit == 0 || english_break_unit == 1 {
let start = i;
let mut max_fs = 0.0f64;
while i < text_len {
let c = text_chars[i];
if soft_hyphen_control && c == '\u{00AD}' {
break;
}
if c == ' ' || c == '\n' || c == '\t' {
break;
}
if !is_latin(c) && !stays_in_latin_word(c) {
break;
}
if english_break_unit == 1 && c == '-' && i > start {
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let lang = 1usize; let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
if fs > max_fs {
max_fs = fs;
}
i += 1;
break; }
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let lang = if is_lang_neutral(c) {
current_lang
} else {
current_lang = 1; 1
};
let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
if fs > max_fs {
max_fs = fs;
}
i += 1;
}
if i > start {
let (width, _) = try_measure_token_chars(
&metric_scope,
&text_chars[start..i],
start,
char_offsets,
char_shapes,
styles,
current_lang,
inline_controls,
false,
storage,
)?;
let mut cw = storage.vec(i - start)?;
for ci in start..i {
let c = text_chars[ci];
let u16p = if ci < char_offsets.len() {
char_offsets[ci]
} else {
ci as u32
};
let sid = find_active_char_shape(char_shapes, u16p);
let lang = if is_lang_neutral(c) { current_lang } else { 1 };
let ts = metric_scope.try_style(styles, sid, lang, ci, storage)?;
cw.push(
reflow_scalar_width(c, &ts)
+ inline_width_px_at(inline_controls, ci, styles),
);
}
storage.push(
&mut tokens,
BreakToken::Text {
start_idx: start,
end_idx: i,
base_width: width,
width,
max_font_size: max_fs,
base_char_widths: storage.copy_slice(&cw)?,
char_widths: cw,
},
)?;
}
continue;
} else {
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
current_lang = 1;
let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
let w =
reflow_scalar_width(ch, &ts) + inline_width_px_at(inline_controls, i, styles);
storage.push(
&mut tokens,
BreakToken::Text {
start_idx: i,
end_idx: i + 1,
base_width: w,
width: w,
max_font_size: fs,
base_char_widths: vec![],
char_widths: vec![],
},
)?;
i += 1;
continue;
}
}
{
let utf16_pos = if i < char_offsets.len() {
char_offsets[i]
} else {
i as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let lang = if is_lang_neutral(ch) {
current_lang
} else {
let detected = detect_lang_category(ch);
current_lang = detected;
detected
};
let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
let fs = token_line_font_size(styles, style_id);
let w = reflow_scalar_width(ch, &ts) + inline_width_px_at(inline_controls, i, styles);
storage.push(
&mut tokens,
BreakToken::Text {
start_idx: i,
end_idx: i + 1,
base_width: w,
width: w,
max_font_size: fs,
base_char_widths: vec![],
char_widths: vec![],
},
)?;
i += 1;
}
}
Ok(tokens)
}
fn reflow_scalar_width(ch: char, style: &crate::renderer::TextStyle) -> f64 {
let display = super::verified_pua_replay_scalar(ch).unwrap_or(ch);
let mut bytes = [0u8; 4];
estimate_text_width_unrounded(display.encode_utf8(&mut bytes), style)
}
fn measure_token_width(
metric_scope: &ParagraphMetricScope,
text: &str,
start_char_idx: usize,
char_offsets: &[u32],
char_shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
default_lang: usize,
inline_controls: &[FlowInlineControl],
) -> f64 {
let mut iter = text.chars();
let first = iter.next();
if let Some(first) = first.filter(|_| iter.clone().next().is_none()) {
return match try_measure_token_chars(
metric_scope,
std::slice::from_ref(&first),
start_char_idx,
char_offsets,
char_shapes,
styles,
default_lang,
inline_controls,
false,
&crate::renderer::style_resolver::storage::Unbounded,
) {
Ok((width, _)) => width,
Err(never) => match never {},
};
}
let chars: Vec<_> = text.chars().collect();
match try_measure_token_chars(
metric_scope,
&chars,
start_char_idx,
char_offsets,
char_shapes,
styles,
default_lang,
inline_controls,
false,
&crate::renderer::style_resolver::storage::Unbounded,
) {
Ok((width, _)) => width,
Err(never) => match never {},
}
}
fn metric_display<'a, S: crate::renderer::style_resolver::storage::Storage>(
chars: &[char],
single: &'a mut [u8; 4],
storage: &S,
) -> Result<std::borrow::Cow<'a, str>, S::Error> {
if let [scalar] = chars {
let scalar = super::verified_pua_replay_scalar(*scalar).unwrap_or(*scalar);
return Ok(std::borrow::Cow::Borrowed(scalar.encode_utf8(single)));
}
Ok(std::borrow::Cow::Owned(
storage.chars(
chars
.iter()
.copied()
.map(|c| super::verified_pua_replay_scalar(c).unwrap_or(c)),
)?,
))
}
fn try_measure_token_chars<S: crate::renderer::style_resolver::storage::Storage>(
metric_scope: &ParagraphMetricScope,
chars: &[char],
start_char_idx: usize,
char_offsets: &[u32],
char_shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
default_lang: usize,
inline_controls: &[FlowInlineControl],
retain_widths: bool,
storage: &S,
) -> Result<(f64, Vec<f64>), S::Error> {
let mut total = 0.0;
let mut char_widths = if retain_widths {
storage.vec(chars.len())?
} else {
Vec::new()
};
let mut current_lang = default_lang;
let mut offset = 0;
while offset < chars.len() {
let ch = chars[offset];
let idx = start_char_idx + offset;
let cluster_end = hangul_jamo_cluster_end(&chars, offset);
let utf16_pos = if idx < char_offsets.len() {
char_offsets[idx]
} else {
idx as u32
};
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let lang = if is_lang_neutral(ch) {
current_lang
} else {
let detected = detect_lang_category(ch);
current_lang = detected;
detected
};
let ts = metric_scope.try_style(styles, style_id, lang, idx, storage)?;
let mut single = [0u8; 4];
let display = metric_display(&chars[offset..cluster_end], &mut single, storage)?;
let width = estimate_text_width_unrounded(&display, &ts)
+ inline_width_px_at(inline_controls, idx, styles);
total += width;
if retain_widths {
char_widths.push(width);
}
for tail in offset + 1..cluster_end {
let tail_width = inline_width_px_at(inline_controls, start_char_idx + tail, styles);
total += tail_width;
if retain_widths {
char_widths.push(tail_width);
}
}
offset = cluster_end;
}
Ok((total, char_widths))
}
fn hangul_jamo_cluster_end(chars: &[char], start: usize) -> usize {
let is_choseong =
|c: char| ('\u{1100}'..='\u{115F}').contains(&c) || ('\u{A960}'..='\u{A97F}').contains(&c);
let is_jungseong =
|c: char| ('\u{1160}'..='\u{11A7}').contains(&c) || ('\u{D7B0}'..='\u{D7C6}').contains(&c);
let is_jongseong =
|c: char| ('\u{11A8}'..='\u{11FF}').contains(&c) || ('\u{D7CB}'..='\u{D7FB}').contains(&c);
if !chars.get(start).is_some_and(|&c| is_choseong(c)) {
return start + 1;
}
let mut end = start + 1;
if chars.get(end).is_some_and(|&c| is_jungseong(c)) {
end += 1;
if chars.get(end).is_some_and(|&c| is_jongseong(c)) {
end += 1;
}
}
end
}
fn inline_width_px_at(
inline_controls: &[FlowInlineControl],
char_idx: usize,
styles: &ResolvedStyleSet,
) -> f64 {
let dpi = styles.resolved_dpi.unwrap_or(crate::renderer::DEFAULT_DPI);
inline_controls
.iter()
.filter(|control| control.char_position == char_idx)
.map(|control| hwpunit_to_px(control.width_hwp, dpi))
.sum()
}
fn prepare_paragraph_projection(
para: &Paragraph,
text_chars: &[char],
styles: &ResolvedStyleSet,
space_metric: SpaceMetric,
inline_controls: &[FlowInlineControl],
) -> Option<PreparedParagraphProjection> {
if text_chars.is_empty() {
return None;
}
let mut current_lang = 0usize;
let mut base_positions = Vec::with_capacity(text_chars.len().saturating_add(1));
let metric_scope = ParagraphMetricScope::new(text_chars, styles)
.with_space_metric(space_metric)
.with_literal_figure_spaces(¶.literal_figure_spaces);
let mut kerning_scalar_styles = Vec::with_capacity(text_chars.len());
let mut shaping_scalar_styles = Vec::with_capacity(text_chars.len());
let mut hard_boundaries = vec![false; text_chars.len().saturating_add(1)];
let mut pen = 0.0f64;
base_positions.push(pen);
for (index, character) in text_chars.iter().copied().enumerate() {
let language_index = if is_lang_neutral(character) {
current_lang
} else {
let detected = detect_lang_category(character);
current_lang = detected;
detected
};
let utf16_pos = para
.char_offsets
.get(index)
.copied()
.unwrap_or(index as u32);
let char_shape_id = find_active_char_shape(¶.char_shapes, utf16_pos);
let text_style = metric_scope.style(styles, char_shape_id, language_index, index);
let base_font_size = text_style.effective_font_size();
let effective_font_size_px = text_style.script_font_size(base_font_size);
let width_ratio = if text_style.ratio > 0.0 {
text_style.ratio
} else {
1.0
};
let slot = crate::renderer::kerning::ExactFontSlot::new(char_shape_id, language_index);
kerning_scalar_styles.push(crate::renderer::kerning::KerningParagraphScalarStyle {
slot,
requested: text_style.kerning,
effective_font_size_px,
width_ratio,
});
shaping_scalar_styles.push(
crate::renderer::shaping_paragraph::HorizontalShapingParagraphScalarStyle {
slot,
effective_font_size_px,
width_ratio,
letter_spacing_px: text_style.letter_spacing,
kerning: text_style.kerning,
bold: text_style.bold,
italic: text_style.italic,
superscript: text_style.superscript,
subscript: text_style.subscript,
},
);
let scalar_width = match character {
'\u{FFFC}'
if inline_controls
.iter()
.any(|control| control.char_position == index) =>
{
0.0
}
'\t' | '\n' | '\r' => 0.0,
' ' => space_metric.space_advance(&text_style),
_ => reflow_scalar_width(character, &text_style),
} + inline_width_px_at(inline_controls, index, styles);
pen += scalar_width.max(0.0);
base_positions.push(pen);
}
for control in inline_controls {
let boundary = control.char_position.min(text_chars.len());
hard_boundaries[boundary] = true;
if boundary < text_chars.len() {
hard_boundaries[boundary + 1] = true;
}
}
Some(PreparedParagraphProjection {
base_positions,
kerning_scalar_styles,
shaping_scalar_styles,
hard_boundaries,
})
}
fn prepare_paragraph_kerning(
para: &Paragraph,
text_chars: &[char],
styles: &ResolvedStyleSet,
space_metric: SpaceMetric,
inline_controls: &[FlowInlineControl],
) -> Option<PreparedParagraphKerning> {
if !para.layout_field_values.is_empty() {
return None;
}
let paragraph_requests_kerning = if para.char_shapes.is_empty() {
styles
.char_styles
.first()
.is_some_and(|style| style.kerning)
} else {
para.char_shapes.iter().any(|shape| {
styles
.char_styles
.get(shape.char_shape_id as usize)
.is_some_and(|style| style.kerning)
})
};
if !paragraph_requests_kerning {
return None;
}
let context = styles.kerning_measurement_context.as_ref()?.clone();
let projection =
prepare_paragraph_projection(para, text_chars, styles, space_metric, inline_controls)?;
if !projection
.kerning_scalar_styles
.iter()
.any(|style| style.requested)
{
return None;
}
let measurement = context.paragraph_measurement(
¶.text,
projection.base_positions,
&projection.kerning_scalar_styles,
&projection.hard_boundaries,
);
if measurement.disposition
!= crate::renderer::kerning::KerningParagraphMeasurementDisposition::PairAdjusted
{
return None;
}
Some(PreparedParagraphKerning {
context,
scalar_styles: projection.kerning_scalar_styles,
hard_boundaries: projection.hard_boundaries,
measurement,
})
}
fn has_rtl_or_bidi_control(text: &str) -> bool {
text.chars().any(|character| {
matches!(
character as u32,
0x0590..=0x08FF
| 0xFB1D..=0xFDFF
| 0xFE70..=0xFEFF
| 0x10800..=0x10FFF
| 0x1E800..=0x1EEFF
| 0x200E..=0x200F
| 0x202A..=0x202E
| 0x2066..=0x2069
)
})
}
pub(super) fn compose_horizontal_shaping_handoff(
para: &Paragraph,
composed: &ComposedParagraph,
styles: &ResolvedStyleSet,
) -> Option<std::sync::Arc<crate::renderer::shaping_paragraph::HorizontalShapingLineOutcome>> {
let kerning_context = styles.kerning_measurement_context.as_ref()?;
let shaping_context = styles.horizontal_shaping_context.as_ref()?;
if kerning_context.registry_generation() != shaping_context.registry_generation() {
return None;
}
let q2_candidate =
crate::renderer::shaping_paragraph::is_bounded_horizontal_shaping_candidate_text(
¶.text,
);
if !q2_candidate && shaping_context.instance_request_count() == 0 {
return None;
}
let text_chars = para.text.chars().collect::<Vec<_>>();
let inline_controls = flow_inline_controls(para, styles);
let projection = prepare_paragraph_projection(
para,
&text_chars,
styles,
SpaceMetric::Stored,
&inline_controls,
)?;
let kerning_measurement = kerning_context.paragraph_measurement(
¶.text,
projection.base_positions.clone(),
&projection.kerning_scalar_styles,
&projection.hard_boundaries,
);
let (fallback_positions, fallback_owner) = if kerning_measurement.disposition
== crate::renderer::kerning::KerningParagraphMeasurementDisposition::PairAdjusted
{
(
kerning_measurement.positions(),
crate::renderer::shaping_paragraph::HorizontalShapingFallbackOwner::W9K1,
)
} else {
(
projection.base_positions.as_slice(),
crate::renderer::shaping_paragraph::HorizontalShapingFallbackOwner::ExistingK0,
)
};
let code_point_count = text_chars.len();
let mut candidate_boundaries = composed
.lines
.iter()
.map(|line| line.char_start)
.chain(std::iter::once(code_point_count))
.collect::<Vec<_>>();
candidate_boundaries.sort_unstable();
candidate_boundaries.dedup();
if candidate_boundaries
.iter()
.any(|index| *index > code_point_count)
{
return None;
}
let available_widths_px = composed
.lines
.iter()
.map(|line| hwpunit_to_px(line.segment_width, 96.0))
.collect::<Vec<_>>();
if available_widths_px.is_empty()
|| available_widths_px
.iter()
.any(|width| !width.is_finite() || *width <= 0.0)
{
return None;
}
let composed_text = composed
.lines
.iter()
.flat_map(|line| line.runs.iter())
.map(|run| run.text.as_str())
.collect::<String>();
let has_char_overlap = composed
.lines
.iter()
.flat_map(|line| line.runs.iter())
.any(|run| run.char_overlap.is_some());
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let paragraph = crate::renderer::shaping_paragraph::HorizontalShapingParagraphRequest {
attempt_id_base: 1,
text: ¶.text,
fallback_positions,
scalar_styles: &projection.shaping_scalar_styles,
hard_boundaries: &projection.hard_boundaries,
fallback_owner,
model_text_matches_shaping_text: composed_text == para.text,
horizontal_ltr_bidi0: !has_rtl_or_bidi_control(¶.text),
condense_min_space: para_style
.map(|style| style.condense_min_space)
.unwrap_or(0),
has_inline_controls: !para.controls.is_empty(),
has_tabs: para.text.contains('\t'),
has_rotation: false,
has_char_overlap,
};
let request = crate::renderer::shaping_paragraph::HorizontalShapingLineRequest {
paragraph,
candidate_boundaries: &candidate_boundaries,
available_widths_px: &available_widths_px,
};
let outcome = if q2_candidate {
let mut transaction = shaping_context.transaction();
std::sync::Arc::new(
crate::renderer::shaping_paragraph::run_horizontal_shaping_line_transaction(
&mut transaction,
&request,
),
)
} else {
let line = composed.lines.first()?;
let run = line.runs.first()?;
if composed.lines.len() != 1
|| line.runs.len() != 1
|| line.has_line_break
|| line.char_start != 0
|| run.text != para.text
|| run.display_text.is_some()
{
return None;
}
let slot = projection.shaping_scalar_styles.first()?.slot;
let mut transaction = shaping_context.explicit_instance_transaction(slot).ok()?;
if transaction.is_default_instance() {
return None;
}
if !crate::renderer::shaping_paragraph::is_bounded_explicit_instance_candidate_text(
¶.text,
) {
return None;
}
std::sync::Arc::new(
crate::renderer::shaping_paragraph::run_bounded_explicit_instance_line_transaction(
&mut transaction,
&request,
),
)
};
crate::renderer::shaping_composition::retain_qualified_horizontal_shaping_outcome(outcome)
}
fn apply_paragraph_kerning_to_tokens(
tokens: &mut [BreakToken],
measurement: &crate::renderer::kerning::KerningParagraphMeasurement,
) -> Option<()> {
for token in tokens {
let BreakToken::Text {
start_idx,
end_idx,
width,
char_widths,
..
} = token
else {
continue;
};
*width = measurement.range_width(*start_idx, *end_idx)?;
*char_widths = (*start_idx..*end_idx)
.map(|index| measurement.range_width(index, index + 1))
.collect::<Option<Vec<_>>>()?;
}
Some(())
}
#[inline]
fn to_hwp(px: f64) -> i32 {
let scaled = px * 75.0;
let nearest = scaled.round();
if (scaled - nearest).abs() <= 1e-6 {
nearest as i32
} else {
scaled as i32
}
}
fn space_is_line_leading(text_chars: &[char], line_start: usize, space_idx: usize) -> bool {
text_chars
.get(line_start..space_idx)
.is_none_or(|before| before.iter().all(|c| *c == ' '))
}
fn condense_space_savings_hwp(space_width_hwp: i32, condense_min_space: u8) -> i32 {
if condense_min_space == 0 || space_width_hwp <= 0 {
return 0;
}
let shrink_percent = condense_min_space.min(75) as i32;
space_width_hwp * shrink_percent / 100
}
pub(crate) fn condense_space_savings_px(space_width_px: f64, percent: u8, dpi: f64) -> f64 {
let source_width = to_hwp(space_width_px * crate::renderer::DEFAULT_DPI / dpi);
crate::renderer::hwpunit_to_px(condense_space_savings_hwp(source_width, percent), dpi)
}
fn condensed_line_width_hwp(width_hwp: i32, space_savings_hwp: i32) -> i32 {
width_hwp - space_savings_hwp
}
fn first_interword_separator(
tokens: &[BreakToken],
token_index: usize,
text_chars: &[char],
line_start: usize,
) -> bool {
let Some(BreakToken::Space {
idx, inline_width, ..
}) = tokens.get(token_index)
else {
return false;
};
if *idx <= line_start
|| *inline_width != 0.0
|| text_chars.get(*idx) != Some(&' ')
|| !text_chars
.get(idx - 1)
.is_some_and(|ch| !ch.is_whitespace() && !ch.is_control() && *ch != '\u{FFFC}')
{
return false;
}
let mut next_index = idx + 1;
let mut additional_space = false;
for token in tokens.iter().skip(token_index + 1) {
match token {
BreakToken::Space {
idx, inline_width, ..
} if *idx == next_index
&& *inline_width == 0.0
&& text_chars.get(*idx) == Some(&' ') =>
{
additional_space = true;
next_index += 1;
}
BreakToken::Text {
start_idx,
end_idx,
width,
..
} => {
return additional_space
&& *start_idx == next_index
&& end_idx > start_idx
&& *width > 0.0;
}
_ => return false,
}
}
false
}
pub(crate) fn overflowing_space_cut(
line_start: usize,
space_idx: usize,
width_hwp: i32,
savings_hwp: i32,
available_hwp: i32,
inline_object_end: Option<(i32, i32)>,
) -> Option<usize> {
if condensed_line_width_hwp(width_hwp, savings_hwp) <= available_hwp {
None
} else if inline_object_end.is_none_or(|(object_end_hwp, object_savings_hwp)| {
condensed_line_width_hwp(object_end_hwp, object_savings_hwp) <= available_hwp
}) {
Some(space_idx + 1)
} else if space_idx > line_start {
Some(space_idx)
} else {
None
}
}
const LINE_BREAK_TOLERANCE_MIN_HWP: i32 = 15;
const LINE_BREAK_TOLERANCE_MAX_HWP: i32 = 50;
const LINE_BREAK_TOLERANCE_WIDTH_PER_HWP: i32 = 760;
#[inline]
fn line_break_tolerance_hwp(box_width_hwp: i32) -> i32 {
(box_width_hwp.max(0) / LINE_BREAK_TOLERANCE_WIDTH_PER_HWP)
.clamp(LINE_BREAK_TOLERANCE_MIN_HWP, LINE_BREAK_TOLERANCE_MAX_HWP)
}
fn new_word_natural_before_hwp(
tokens: &[BreakToken],
token_idx: usize,
line_start: usize,
) -> Option<i32> {
let mut k = token_idx;
while k > 0 {
match &tokens[k - 1] {
BreakToken::Space { idx, .. } if *idx >= line_start => k -= 1,
_ => break,
}
}
if k == token_idx {
return None;
}
let width = recalc_width_hwp(tokens, k, line_start);
(width > 0).then_some(width)
}
fn punct_latin_slot(styles: &ResolvedStyleSet, style_id: u32) -> bool {
styles
.char_styles
.get(style_id as usize)
.is_some_and(|style| style.ascii_punct_latin_slot)
}
fn fit_test_letter_spacing_trim_hwp(letter_spacing_px: &[f64], token_end_idx: usize) -> i32 {
if token_end_idx == 0 {
return 0;
}
letter_spacing_px
.get(token_end_idx - 1)
.map(|spacing| to_hwp(*spacing))
.unwrap_or(0)
}
fn resolved_letter_spacing_px(
chars: &[char],
offsets: &[u32],
shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
space: SpaceMetric,
literal_figure_spaces: &[usize],
) -> Vec<f64> {
match try_resolved_letter_spacing_px(
chars,
offsets,
shapes,
styles,
space,
literal_figure_spaces,
&Unbounded,
) {
Ok(values) => values,
Err(never) => match never {},
}
}
fn try_resolved_letter_spacing_px<S: Storage>(
text_chars: &[char],
char_offsets: &[u32],
char_shapes: &[CharShapeRef],
styles: &ResolvedStyleSet,
space_metric: SpaceMetric,
literal_figure_spaces: &[usize],
storage: &S,
) -> Result<Vec<f64>, S::Error> {
let mut lang = 0usize;
let metric_scope = ParagraphMetricScope::try_new(text_chars, styles, storage)?
.with_space_metric(space_metric)
.with_literal_figure_spaces(literal_figure_spaces);
let mut values = storage.vec(text_chars.len())?;
for (idx, ch) in text_chars.iter().enumerate() {
let utf16_pos = char_offsets.get(idx).copied().unwrap_or(idx as u32);
let style_id = find_active_char_shape(char_shapes, utf16_pos);
let char_lang = char_lang_slot(*ch, &mut lang, punct_latin_slot(styles, style_id));
let spacing_lang = super::punctuation_slots::metric_slot(*ch, char_lang, styles, style_id);
if resolved_letter_spacing(styles, style_id, spacing_lang) == 0.0 {
values.push(0.0);
continue;
}
let style = metric_scope.try_style(styles, style_id, char_lang, idx, storage)?;
values.push(glyph_letter_spacing_advance(
ch.encode_utf8(&mut [0; 4]),
&style,
));
}
Ok(values)
}
fn resolved_paragraph_letter_spacing(
para: &Paragraph,
chars: &[char],
styles: &ResolvedStyleSet,
space: SpaceMetric,
) -> Vec<f64> {
match try_resolved_paragraph_letter_spacing(para, chars, styles, space, &Unbounded) {
Ok(values) => values,
Err(never) => match never {},
}
}
fn try_resolved_paragraph_letter_spacing<S: Storage>(
para: &Paragraph,
text_chars: &[char],
styles: &ResolvedStyleSet,
space_metric: SpaceMetric,
storage: &S,
) -> Result<Vec<f64>, S::Error> {
let mut values = try_resolved_letter_spacing_px(
text_chars,
¶.char_offsets,
¶.char_shapes,
styles,
space_metric,
¶.literal_figure_spaces,
storage,
)?;
for (position, value) in ¶.layout_field_values {
if let Some(spacing) = values.get_mut(*position) {
let shape = para.char_shape_id_at(*position).unwrap_or(0);
let lang = value.chars().next().map(detect_lang_category).unwrap_or(0);
*spacing = resolved_letter_spacing(styles, shape, lang);
}
}
Ok(values)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FitWidthHwp(i32);
impl FitWidthHwp {
fn trimmed(token_width_hwp: i32, letter_spacing_px: &[f64], token_end_idx: usize) -> Self {
Self(token_width_hwp - fit_test_letter_spacing_trim_hwp(letter_spacing_px, token_end_idx))
}
fn with_pair_adjustment(self, adjustment_hwp: i32) -> Self {
Self(self.0 + adjustment_hwp)
}
}
fn list_marker_breaker_box(
para: &Paragraph,
styles: &ResolvedStyleSet,
indent_px: f64,
) -> (f64, f64) {
crate::renderer::layout::list_marker_geometry(para, styles)
.map_or((0.0, indent_px), |geometry| geometry.breaker_box(indent_px))
}
fn text_token_fits_line_hwp(
current_width_hwp: i32,
token_width: FitWidthHwp,
space_savings_hwp: i32,
effective_width_hwp: i32,
new_word_natural_before_hwp: Option<i32>,
) -> bool {
text_token_fits_in_line_with_tolerance_hwp(
current_width_hwp,
token_width,
space_savings_hwp,
effective_width_hwp,
new_word_natural_before_hwp,
line_break_tolerance_hwp(effective_width_hwp),
)
}
fn text_token_fits_in_line_with_tolerance_hwp(
current_width_hwp: i32,
token_width: FitWidthHwp,
space_savings_hwp: i32,
effective_width_hwp: i32,
new_word_natural_before_hwp: Option<i32>,
tolerance_hwp: i32,
) -> bool {
let natural_candidate = current_width_hwp + token_width.0;
let condensed_candidate = condensed_line_width_hwp(natural_candidate, space_savings_hwp);
let limit_hwp = effective_width_hwp + tolerance_hwp;
if natural_candidate <= limit_hwp {
return true;
}
if condensed_candidate > effective_width_hwp {
return false;
}
!new_word_natural_before_hwp.is_some_and(|w| w >= effective_width_hwp)
}
#[derive(Debug, Clone)]
struct FillCursor {
token_index: usize,
fallback_char_idx: Option<usize>,
initial_start_idx: usize,
line_start_idx: usize,
lw: i32,
line_space_savings: i32,
line_max_fs: f64,
is_first_line: bool,
last_break_token_idx: Option<usize>,
last_break_char_idx: usize,
width_at_last_break: i32,
space_savings_at_last_break: i32,
fs_at_last_break: f64,
word_gap_natural_hwp: Option<i32>,
allow_metric_tolerance: bool,
tab_grid_origin_px: Option<f64>,
finished: bool,
emitted_any: bool,
}
impl FillCursor {
fn new(initial_start_idx: usize, initial_is_first_line: bool) -> Self {
Self {
token_index: 0,
fallback_char_idx: None,
initial_start_idx,
line_start_idx: initial_start_idx,
lw: 0,
line_space_savings: 0,
line_max_fs: 0.0,
is_first_line: initial_is_first_line,
last_break_token_idx: None,
last_break_char_idx: 0,
width_at_last_break: 0,
space_savings_at_last_break: 0,
fs_at_last_break: 0.0,
word_gap_natural_hwp: None,
allow_metric_tolerance: true,
tab_grid_origin_px: None,
finished: false,
emitted_any: false,
}
}
fn replay_from_boundary(tokens: &[BreakToken], boundary: usize, first_line: bool) -> Self {
let mut cursor = Self::new(boundary, first_line);
cursor.token_index = first_token_at_or_after(tokens, boundary);
if let Some(BreakToken::Text { start_idx, .. }) = tokens.get(cursor.token_index) {
if boundary > *start_idx {
cursor.fallback_char_idx = Some(boundary);
}
}
cursor
}
}
#[derive(Clone, Copy)]
struct TabFill<'a> {
default_width_px: f64,
stops: &'a [crate::renderer::TabStop],
auto_tab_right: bool,
line_origin_px: [f64; 2],
available_width_px: f64,
stop_overflow_wraps: bool,
}
impl<'a> TabFill<'a> {
fn default_only(default_width_px: f64) -> Self {
Self {
default_width_px,
stops: &[],
auto_tab_right: false,
line_origin_px: [0.0, 0.0],
available_width_px: 0.0,
stop_overflow_wraps: false,
}
}
fn for_paragraph(
para_style: Option<&'a ResolvedParaStyle>,
indent_px: f64,
available_width_px: f64,
) -> Self {
let Some(style) = para_style else {
return Self::default_only(0.0);
};
Self {
default_width_px: style.default_tab_width,
stops: &style.tab_stops,
auto_tab_right: style.auto_tab_right,
line_origin_px: [
style.margin_left + indent_px.max(0.0),
style.margin_left + (-indent_px).max(0.0),
],
available_width_px,
stop_overflow_wraps: false,
}
}
fn with_stop_overflow_wraps(mut self, styles: &ResolvedStyleSet) -> Self {
self.stop_overflow_wraps = !styles.word_compat_target;
self
}
fn default_width(&self) -> f64 {
if self.default_width_px > 0.0 {
self.default_width_px
} else {
48.0
}
}
fn next_hwp(&self, lw_hwp: i32, first_line: bool, origin_override: Option<f64>) -> i32 {
let lw_px = lw_hwp as f64 / 75.0;
let origin = origin_override.unwrap_or(self.line_origin_px[usize::from(!first_line)]);
let (position, tab_type, _) = crate::renderer::layout::find_next_tab_stop(
origin + lw_px,
self.stops,
self.default_width(),
self.auto_tab_right,
self.available_width_px,
origin,
);
match tab_type {
0 | 3 => to_hwp(position - origin).max(lw_hwp),
_ => to_hwp(((lw_px / self.default_width()).floor() + 1.0) * self.default_width()),
}
}
fn explicit_stop_beyond_line(
&self,
lw_hwp: i32,
first_line: bool,
origin_override: Option<f64>,
line_width_hwp: i32,
) -> bool {
if !self.stop_overflow_wraps {
return false;
}
let origin = origin_override.unwrap_or(self.line_origin_px[usize::from(!first_line)]);
let x = origin + lw_hwp as f64 / 75.0;
let right_edge = origin + line_width_hwp as f64 / 75.0;
self.stops
.iter()
.find(|stop| stop.position > x + 0.5)
.is_some_and(|stop| stop.tab_type != 1 && stop.position > right_edge + 0.5)
}
}
fn apply_auto_left_tab_targets(
tokens: &mut [BreakToken],
style: Option<&super::super::style_resolver::ResolvedParaStyle>,
) {
let target = style
.filter(|style| style.auto_tab_left)
.map(|style| -style.indent)
.filter(|target| *target > 0.0);
for token in tokens {
if let BreakToken::Tab {
auto_left_target, ..
} = token
{
*auto_left_target = target;
}
}
}
fn fill_lines(
tokens: &[BreakToken],
text_chars: &[char],
available_width_px: f64,
indent_px: f64,
tabs: TabFill<'_>,
korean_break_unit: u8,
condense_min_space: u8,
letter_spacing_px: &[f64],
initial_start_idx: usize,
initial_is_first_line: bool,
allow_metric_tolerance: bool,
kerning: Option<&mut crate::renderer::kerning::KerningParagraphBreakSession<'_, '_, '_>>,
) -> Vec<LineBreakResult> {
match try_fill_lines(
tokens,
text_chars,
available_width_px,
indent_px,
tabs,
korean_break_unit,
condense_min_space,
letter_spacing_px,
initial_start_idx,
initial_is_first_line,
allow_metric_tolerance,
kerning,
&Unbounded,
) {
Ok(lines) => lines,
Err(never) => match never {},
}
}
fn try_fill_lines<S: Storage>(
tokens: &[BreakToken],
text_chars: &[char],
available_width_px: f64,
indent_px: f64,
tabs: TabFill<'_>,
korean_break_unit: u8,
condense_min_space: u8,
letter_spacing_px: &[f64],
initial_start_idx: usize,
initial_is_first_line: bool,
allow_metric_tolerance: bool,
mut kerning: Option<&mut crate::renderer::kerning::KerningParagraphBreakSession<'_, '_, '_>>,
storage: &S,
) -> Result<Vec<LineBreakResult>, S::Error> {
let mut cursor = FillCursor::new(initial_start_idx, initial_is_first_line);
cursor.allow_metric_tolerance = allow_metric_tolerance;
let mut results = Vec::new();
while let Some(interval) = fill_one_interval(
tokens,
text_chars,
available_width_px,
indent_px,
tabs,
korean_break_unit,
condense_min_space,
letter_spacing_px,
&mut cursor,
kerning.as_deref_mut(),
) {
storage.push(&mut results, interval.line)?;
}
Ok(results)
}
fn fill_one_interval(
tokens: &[BreakToken],
text_chars: &[char],
available_width_px: f64,
indent_px: f64,
tabs: TabFill<'_>,
korean_break_unit: u8,
condense_min_space: u8,
letter_spacing_px: &[f64],
cursor: &mut FillCursor,
mut kerning: Option<&mut crate::renderer::kerning::KerningParagraphBreakSession<'_, '_, '_>>,
) -> Option<FilledInterval> {
let allow_metric_tolerance = cursor.allow_metric_tolerance;
let fits_physical_line = |current, token, savings, width, word| {
text_token_fits_in_line_with_tolerance_hwp(
current,
token,
savings,
width,
word,
if allow_metric_tolerance {
line_break_tolerance_hwp(width)
} else {
0
},
)
};
if cursor.finished {
return None;
}
if tokens.is_empty() {
cursor.finished = true;
cursor.emitted_any = true;
return Some(FilledInterval {
line: LineBreakResult {
start_idx: cursor.initial_start_idx,
end_idx: cursor.initial_start_idx,
max_font_size: 0.0,
has_line_break: false,
},
termination: FillTermination::ParagraphEnd,
});
}
let eff_w = |first: bool| -> i32 {
if indent_px > 0.0 {
if first {
to_hwp((available_width_px - indent_px).max(1.0))
} else {
to_hwp(available_width_px)
}
} else if indent_px < 0.0 {
if first {
to_hwp(available_width_px)
} else {
to_hwp((available_width_px + indent_px).max(1.0))
}
} else {
to_hwp(available_width_px)
}
};
loop {
if cursor.token_index >= tokens.len() {
cursor.finished = true;
let last_end = tokens
.last()
.map(|token| match token {
BreakToken::Text { end_idx, .. } => *end_idx,
BreakToken::DiscretionaryHyphen { idx, .. }
| BreakToken::Space { idx, .. }
| BreakToken::Tab { idx, .. }
| BreakToken::LineBreak { idx } => *idx + 1,
})
.unwrap_or(text_chars.len());
if cursor.line_start_idx <= last_end {
cursor.emitted_any = true;
return Some(FilledInterval {
line: LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: last_end,
max_font_size: cursor.line_max_fs,
has_line_break: false,
},
termination: FillTermination::ParagraphEnd,
});
}
if !cursor.emitted_any {
cursor.emitted_any = true;
return Some(FilledInterval {
line: LineBreakResult {
start_idx: cursor.initial_start_idx,
end_idx: text_chars.len(),
max_font_size: 0.0,
has_line_break: false,
},
termination: FillTermination::ParagraphEnd,
});
}
return None;
}
let ti = cursor.token_index;
match &tokens[ti] {
BreakToken::DiscretionaryHyphen {
idx,
width,
max_font_size,
} => {
let size = cursor.line_max_fs.max(*max_font_size);
if *idx > cursor.line_start_idx
&& fits_physical_line(
cursor.lw,
FitWidthHwp(to_hwp(*width)),
cursor.line_space_savings,
eff_w(cursor.is_first_line),
None,
)
{
cursor.last_break_token_idx = Some(ti);
cursor.last_break_char_idx = *idx + 1;
cursor.width_at_last_break = cursor.lw;
cursor.space_savings_at_last_break = cursor.line_space_savings;
cursor.fs_at_last_break = size;
}
cursor.line_max_fs = size;
cursor.token_index += 1;
}
BreakToken::LineBreak { idx } => {
let result = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: *idx + 1,
max_font_size: cursor.line_max_fs,
has_line_break: true,
};
cursor.line_start_idx = *idx + 1;
cursor.lw = 0;
cursor.line_space_savings = 0;
cursor.line_max_fs = 0.0;
cursor.is_first_line = false;
cursor.last_break_token_idx = None;
cursor.token_index += 1;
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::ForcedBreak,
});
}
BreakToken::Tab {
idx,
max_font_size,
auto_left_target,
} => {
cursor.word_gap_natural_hwp = None;
let origin_override = cursor.tab_grid_origin_px.map(|origin| {
origin
+ if (indent_px > 0.0 && cursor.is_first_line)
|| (indent_px < 0.0 && !cursor.is_first_line)
{
indent_px.abs()
} else {
0.0
}
});
let next_tab_hwp = auto_left_target
.filter(|target| cursor.is_first_line && to_hwp(*target) > cursor.lw)
.map(to_hwp)
.unwrap_or_else(|| {
tabs.next_hwp(cursor.lw, cursor.is_first_line, origin_override)
});
if *max_font_size > cursor.line_max_fs {
cursor.line_max_fs = *max_font_size;
}
if auto_left_target.is_none()
&& tokens.len() > ti + 1
&& tabs.explicit_stop_beyond_line(
cursor.lw,
cursor.is_first_line,
origin_override,
eff_w(cursor.is_first_line),
)
{
let tab_leads_line = cursor.line_start_idx == *idx;
let end_idx = if tab_leads_line { *idx + 1 } else { *idx };
let result = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx,
max_font_size: cursor.line_max_fs,
has_line_break: false,
};
cursor.line_start_idx = end_idx;
cursor.lw = 0;
cursor.line_space_savings = 0;
cursor.line_max_fs = 0.0;
cursor.is_first_line = false;
cursor.last_break_token_idx = None;
if tab_leads_line {
cursor.token_index += 1;
}
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
if next_tab_hwp > eff_w(cursor.is_first_line) && cursor.line_start_idx < *idx {
let result = if cursor.last_break_token_idx.is_some() {
let result = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: cursor.last_break_char_idx,
max_font_size: cursor.fs_at_last_break,
has_line_break: false,
};
cursor.line_start_idx = cursor.last_break_char_idx;
cursor.lw -= cursor.width_at_last_break;
cursor.line_space_savings -= cursor.space_savings_at_last_break;
result
} else {
let result = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: *idx,
max_font_size: cursor.line_max_fs,
has_line_break: false,
};
cursor.line_start_idx = *idx;
cursor.lw = 0;
cursor.line_space_savings = 0;
cursor.line_max_fs = *max_font_size;
result
};
cursor.is_first_line = false;
cursor.last_break_token_idx = None;
cursor.lw = tabs.next_hwp(
cursor.lw,
cursor.is_first_line,
cursor
.tab_grid_origin_px
.map(|origin| origin + (-indent_px).max(0.0)),
);
cursor.token_index += 1;
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
cursor.last_break_token_idx = Some(ti);
cursor.last_break_char_idx = *idx;
cursor.width_at_last_break = cursor.lw;
cursor.space_savings_at_last_break = cursor.line_space_savings;
cursor.fs_at_last_break = cursor.line_max_fs;
cursor.lw = next_tab_hwp;
cursor.token_index += 1;
}
BreakToken::Space {
idx,
width,
condense_base,
max_font_size,
inline_width,
} => {
let previous_line_max_fs = cursor.line_max_fs;
if *max_font_size > cursor.line_max_fs {
cursor.line_max_fs = *max_font_size;
}
let space_hwp = to_hwp(*width);
let leading = space_is_line_leading(text_chars, cursor.line_start_idx, *idx);
let space_savings = if leading {
0
} else {
condense_space_savings_hwp(to_hwp(*condense_base), condense_min_space)
};
if let Some(cut) = overflowing_space_cut(
cursor.line_start_idx,
*idx,
cursor.lw + space_hwp,
cursor.line_space_savings + space_savings,
eff_w(cursor.is_first_line),
(*inline_width > 0.0)
.then(|| (cursor.lw + to_hwp(*inline_width), cursor.line_space_savings)),
)
.filter(|_| {
!first_interword_separator(tokens, ti, text_chars, cursor.line_start_idx)
}) {
let mut cut = cut;
let mut hung_extra = 0usize;
let absorbed = cut > *idx;
let word_attached = absorbed
&& *idx > cursor.line_start_idx
&& text_chars.get(*idx - 1).is_some_and(|c| !c.is_whitespace());
if word_attached {
if let Some(BreakToken::Space {
idx: next_idx,
max_font_size: next_fs,
..
}) = tokens.get(ti + 1)
{
if *next_idx == *idx + 1 {
if *next_fs > cursor.line_max_fs {
cursor.line_max_fs = *next_fs;
}
cut = *next_idx + 1;
hung_extra = 1;
}
}
}
if absorbed && ti + 1 + hung_extra == tokens.len() {
cursor.finished = true;
cursor.emitted_any = true;
cursor.token_index = tokens.len();
return Some(FilledInterval {
line: LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: cut,
max_font_size: cursor.line_max_fs,
has_line_break: false,
},
termination: FillTermination::ParagraphEnd,
});
}
let line = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: cut,
max_font_size: if absorbed {
cursor.line_max_fs
} else {
previous_line_max_fs
},
has_line_break: false,
};
cursor.line_start_idx = cut;
cursor.lw = if absorbed { 0 } else { space_hwp };
cursor.line_space_savings = 0;
cursor.line_max_fs = if absorbed { 0.0 } else { *max_font_size };
cursor.is_first_line = false;
cursor.last_break_token_idx = None;
cursor.word_gap_natural_hwp = None;
cursor.token_index += 1 + hung_extra;
cursor.emitted_any = true;
let at_end = absorbed && cursor.token_index == tokens.len();
cursor.finished = at_end;
return Some(FilledInterval {
line,
termination: if at_end {
FillTermination::ParagraphEnd
} else {
FillTermination::IntervalFull
},
});
}
cursor.last_break_token_idx = Some(ti);
cursor.last_break_char_idx = *idx;
cursor.width_at_last_break = cursor.lw;
cursor.space_savings_at_last_break = cursor.line_space_savings;
cursor.fs_at_last_break = cursor.line_max_fs;
if cursor.word_gap_natural_hwp.is_none() && !leading {
cursor.word_gap_natural_hwp = Some(cursor.lw);
}
cursor.lw += space_hwp;
cursor.line_space_savings += space_savings;
cursor.token_index += 1;
}
BreakToken::Text {
start_idx,
end_idx,
base_width,
max_font_size,
base_char_widths,
..
} => {
let new_word_natural = cursor
.word_gap_natural_hwp
.take()
.filter(|_| *start_idx > cursor.line_start_idx);
if let Some(next_char_idx) = cursor.fallback_char_idx {
debug_assert!(*start_idx <= next_char_idx && next_char_idx <= *end_idx);
let mut ci = next_char_idx;
while ci < *end_idx {
let rel_idx = ci - *start_idx;
let char_w = base_char_widths
.get(rel_idx)
.copied()
.or_else(|| (*end_idx == *start_idx + 1).then_some(*base_width))
.map(to_hwp)
.unwrap_or_else(|| {
let ch = text_chars[ci];
let char_w_px = if is_cjk_char(ch) {
cursor.line_max_fs.max(12.0)
} else {
cursor.line_max_fs.max(12.0) * 0.5
};
to_hwp(char_w_px)
});
let current_width = eff_w(cursor.is_first_line);
let candidate_base = cursor.lw + char_w;
let candidate_width = if let Some(session) = kerning.as_deref_mut() {
candidate_base
+ to_hwp(
session
.boundary_pair_adjustment(cursor.line_start_idx, ci + 1)?,
)
} else {
candidate_base
};
if candidate_width > current_width && ci > cursor.line_start_idx {
let result = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: ci,
max_font_size: cursor.line_max_fs,
has_line_break: false,
};
cursor.line_start_idx = ci;
cursor.lw = char_w;
cursor.is_first_line = false;
cursor.fallback_char_idx = Some(ci + 1);
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
cursor.lw += char_w;
ci += 1;
}
cursor.fallback_char_idx = None;
cursor.token_index += 1;
continue;
}
if break_before_text_token(
text_chars,
*start_idx,
cursor.line_start_idx,
korean_break_unit,
) {
cursor.last_break_token_idx = Some(ti - 1);
cursor.last_break_char_idx = *start_idx;
cursor.width_at_last_break = cursor.lw;
cursor.space_savings_at_last_break = cursor.line_space_savings;
cursor.fs_at_last_break = cursor.line_max_fs;
}
if *max_font_size > cursor.line_max_fs {
cursor.line_max_fs = *max_font_size;
}
let w_hwp = to_hwp(*base_width);
let effective_width = eff_w(cursor.is_first_line);
let at_written_line_end = tokens[ti + 1..]
.iter()
.find(|token| {
!matches!(token, BreakToken::Space { inline_width, .. } if *inline_width == 0.0)
})
.is_none_or(|token| matches!(token, BreakToken::LineBreak { .. }));
let w_hwp_fit = if at_written_line_end
&& fit_test_letter_spacing_trim_hwp(letter_spacing_px, *end_idx) < 0
&& cursor.lw + w_hwp
<= effective_width + line_break_tolerance_hwp(effective_width)
{
FitWidthHwp(w_hwp)
} else {
FitWidthHwp::trimmed(w_hwp, letter_spacing_px, *end_idx)
};
let pair_adjustment_hwp = if let Some(session) = kerning.as_deref_mut() {
to_hwp(session.boundary_pair_adjustment(cursor.line_start_idx, *end_idx)?)
} else {
0
};
let token_fits = fits_physical_line(
cursor.lw,
w_hwp_fit.with_pair_adjustment(pair_adjustment_hwp),
cursor.line_space_savings,
effective_width,
new_word_natural,
);
let tail_all_line_start_forbidden = text_chars[*start_idx + 1..*end_idx]
.iter()
.all(|c| is_line_start_forbidden(*c));
if tail_all_line_start_forbidden && token_fits {
let c = text_chars[*start_idx];
let allow_break = can_break_after_text_token(c, korean_break_unit);
if allow_break {
cursor.last_break_token_idx = Some(ti);
cursor.last_break_char_idx = *end_idx; cursor.width_at_last_break = cursor.lw + w_hwp; cursor.space_savings_at_last_break = cursor.line_space_savings;
cursor.fs_at_last_break = cursor.line_max_fs;
}
}
if !token_fits {
if *start_idx > cursor.line_start_idx {
if let Some(break_token_idx) = cursor.last_break_token_idx {
let detached_tail = forbidden_tail_before_oversized_run(
tokens,
text_chars,
break_token_idx,
cursor.line_start_idx,
eff_w(false),
);
if let Some(tail) = detached_tail {
cursor.last_break_char_idx = tail;
}
let result = LineBreakResult {
start_idx: cursor.line_start_idx,
end_idx: cursor.last_break_char_idx,
max_font_size: cursor.fs_at_last_break,
has_line_break: false,
};
let mut next_start = cursor.last_break_char_idx;
while next_start < text_chars.len() && text_chars[next_start] == ' ' {
next_start += 1;
}
cursor.line_start_idx = next_start;
cursor.lw = recalc_width_hwp(tokens, ti, next_start);
cursor.line_space_savings = recalc_space_savings_hwp(
tokens,
ti,
next_start,
condense_min_space,
);
cursor.line_max_fs = *max_font_size;
cursor.is_first_line = false;
cursor.last_break_token_idx = None;
if detached_tail.is_some() || cursor.lw > eff_w(false) {
cursor.token_index = first_token_at_or_after(tokens, next_start);
cursor.lw = 0;
cursor.line_space_savings = 0;
if let Some(BreakToken::Text { start_idx, .. }) =
tokens.get(cursor.token_index)
{
if next_start > *start_idx {
cursor.fallback_char_idx = Some(next_start);
}
}
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
if break_token_idx == ti {
cursor.lw += w_hwp;
cursor.token_index += 1;
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
if fits_physical_line(
cursor.lw,
w_hwp_fit.with_pair_adjustment(
if let Some(session) = kerning.as_deref_mut() {
to_hwp(session.boundary_pair_adjustment(
cursor.line_start_idx,
*end_idx,
)?)
} else {
0
},
),
cursor.line_space_savings,
eff_w(false),
new_word_natural_before_hwp(tokens, ti, cursor.line_start_idx),
) {
cursor.lw += w_hwp;
cursor.token_index += 1;
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
cursor.line_space_savings = 0;
cursor.last_break_token_idx = None;
cursor.fallback_char_idx = Some(*start_idx);
cursor.emitted_any = true;
return Some(FilledInterval {
line: result,
termination: FillTermination::IntervalFull,
});
}
}
cursor.line_space_savings = 0;
cursor.last_break_token_idx = None;
cursor.fallback_char_idx = Some(*start_idx);
continue;
}
cursor.lw += w_hwp;
cursor.token_index += 1;
}
}
}
}
#[cfg(test)]
fn fill_lines_before_cursor(
tokens: &[BreakToken],
text_chars: &[char],
available_width_px: f64,
indent_px: f64,
default_tab_width: f64,
korean_break_unit: u8,
condense_min_space: u8,
initial_start_idx: usize,
initial_is_first_line: bool,
) -> Vec<LineBreakResult> {
if tokens.is_empty() {
return vec![LineBreakResult {
start_idx: initial_start_idx,
end_idx: initial_start_idx,
max_font_size: 0.0,
has_line_break: false,
}];
}
let tab_w_hwp = to_hwp(if default_tab_width > 0.0 {
default_tab_width
} else {
48.0
});
let tab_w_px = if default_tab_width > 0.0 {
default_tab_width
} else {
48.0
};
let mut results = Vec::new();
let mut line_start_idx = initial_start_idx;
let mut lw = 0i32; let mut line_space_savings = 0i32;
let mut line_max_fs = 0.0f64;
let mut is_first_line = initial_is_first_line;
let mut last_break_token_idx: Option<usize> = None;
let mut last_break_char_idx: usize = 0;
let mut width_at_last_break = 0i32;
let mut space_savings_at_last_break = 0i32;
let mut fs_at_last_break = 0.0f64;
let eff_w = |first: bool| -> i32 {
if indent_px > 0.0 {
if first {
to_hwp((available_width_px - indent_px).max(1.0))
} else {
to_hwp(available_width_px)
}
} else if indent_px < 0.0 {
if first {
to_hwp(available_width_px)
} else {
to_hwp((available_width_px + indent_px).max(1.0))
}
} else {
to_hwp(available_width_px)
}
};
for (ti, token) in tokens.iter().enumerate() {
match token {
BreakToken::DiscretionaryHyphen {
idx,
width,
max_font_size,
} => {
line_max_fs = line_max_fs.max(*max_font_size);
if *idx > line_start_idx
&& lw + to_hwp(*width) - line_space_savings <= eff_w(is_first_line)
{
last_break_token_idx = Some(ti);
last_break_char_idx = *idx + 1;
width_at_last_break = lw;
space_savings_at_last_break = line_space_savings;
fs_at_last_break = line_max_fs;
}
}
BreakToken::LineBreak { idx } => {
results.push(LineBreakResult {
start_idx: line_start_idx,
end_idx: *idx + 1,
max_font_size: line_max_fs,
has_line_break: true,
});
line_start_idx = *idx + 1;
lw = 0;
line_space_savings = 0;
line_max_fs = 0.0;
is_first_line = false;
last_break_token_idx = None;
}
BreakToken::Tab {
idx, max_font_size, ..
} => {
let lw_px = lw as f64 / 75.0;
let next_tab_px = ((lw_px / tab_w_px).floor() + 1.0) * tab_w_px;
let next_tab_hwp = to_hwp(next_tab_px);
if *max_font_size > line_max_fs {
line_max_fs = *max_font_size;
}
if next_tab_hwp > eff_w(is_first_line) && line_start_idx < *idx {
if let Some(_) = last_break_token_idx {
results.push(LineBreakResult {
start_idx: line_start_idx,
end_idx: last_break_char_idx,
max_font_size: fs_at_last_break,
has_line_break: false,
});
line_start_idx = last_break_char_idx;
lw = lw - width_at_last_break;
line_space_savings -= space_savings_at_last_break;
} else {
results.push(LineBreakResult {
start_idx: line_start_idx,
end_idx: *idx,
max_font_size: line_max_fs,
has_line_break: false,
});
line_start_idx = *idx;
lw = 0;
line_space_savings = 0;
line_max_fs = *max_font_size;
}
is_first_line = false;
last_break_token_idx = None;
let lw_px2 = lw as f64 / 75.0;
let next_tab2 = ((lw_px2 / tab_w_px).floor() + 1.0) * tab_w_px;
lw = to_hwp(next_tab2);
} else {
last_break_token_idx = Some(ti);
last_break_char_idx = *idx;
width_at_last_break = lw;
space_savings_at_last_break = line_space_savings;
fs_at_last_break = line_max_fs;
lw = next_tab_hwp;
}
}
BreakToken::Space {
idx,
width,
condense_base,
max_font_size,
..
} => {
if *max_font_size > line_max_fs {
line_max_fs = *max_font_size;
}
last_break_token_idx = Some(ti);
last_break_char_idx = *idx;
width_at_last_break = lw;
space_savings_at_last_break = line_space_savings;
fs_at_last_break = line_max_fs;
let space_hwp = to_hwp(*width);
lw += space_hwp;
if !space_is_line_leading(text_chars, line_start_idx, *idx) {
line_space_savings +=
condense_space_savings_hwp(to_hwp(*condense_base), condense_min_space);
}
}
BreakToken::Text {
start_idx,
end_idx,
width,
max_font_size,
ref char_widths,
..
} => {
if break_before_text_token(
text_chars,
*start_idx,
line_start_idx,
korean_break_unit,
) {
last_break_token_idx = Some(ti - 1);
last_break_char_idx = *start_idx;
width_at_last_break = lw;
space_savings_at_last_break = line_space_savings;
fs_at_last_break = line_max_fs;
}
if *max_font_size > line_max_fs {
line_max_fs = *max_font_size;
}
let w_hwp = to_hwp(*width);
let effective_width = eff_w(is_first_line);
let new_word_natural = new_word_natural_before_hwp(tokens, ti, line_start_idx);
let token_fits = text_token_fits_line_hwp(
lw,
FitWidthHwp(w_hwp),
line_space_savings,
effective_width,
new_word_natural,
);
let tail_all_line_start_forbidden = text_chars[*start_idx + 1..*end_idx]
.iter()
.all(|c| is_line_start_forbidden(*c));
if tail_all_line_start_forbidden && token_fits {
let c = text_chars[*start_idx];
let allow_break = can_break_after_text_token(c, korean_break_unit);
if allow_break {
last_break_token_idx = Some(ti);
last_break_char_idx = *end_idx; width_at_last_break = lw + w_hwp; space_savings_at_last_break = line_space_savings;
fs_at_last_break = line_max_fs;
}
}
if !text_token_fits_line_hwp(
lw,
FitWidthHwp(w_hwp),
line_space_savings,
effective_width,
new_word_natural,
) {
if *start_idx > line_start_idx {
if let Some(break_token_idx) = last_break_token_idx {
results.push(LineBreakResult {
start_idx: line_start_idx,
end_idx: last_break_char_idx,
max_font_size: fs_at_last_break,
has_line_break: false,
});
let mut next_start = last_break_char_idx;
while next_start < text_chars.len() && text_chars[next_start] == ' ' {
next_start += 1;
}
line_start_idx = next_start;
lw = recalc_width_hwp(tokens, ti, next_start);
line_space_savings = recalc_space_savings_hwp(
tokens,
ti,
next_start,
condense_min_space,
);
line_max_fs = *max_font_size;
is_first_line = false;
last_break_token_idx = None;
if break_token_idx == ti {
lw += w_hwp;
continue;
}
if text_token_fits_line_hwp(
lw,
FitWidthHwp(w_hwp),
line_space_savings,
eff_w(false),
new_word_natural_before_hwp(tokens, ti, line_start_idx),
) {
lw += w_hwp;
continue;
}
}
}
let cw_hwp: Vec<i32> = char_widths.iter().map(|w| to_hwp(*w)).collect();
let (results_part, remaining_w, remaining_fs) = char_level_break_hwp(
text_chars,
*start_idx,
*end_idx,
&mut line_start_idx,
lw,
line_max_fs,
eff_w(is_first_line),
eff_w(false),
is_first_line,
&cw_hwp,
);
for r in results_part {
results.push(r);
is_first_line = false;
}
lw = remaining_w;
line_space_savings = 0;
line_max_fs = remaining_fs;
last_break_token_idx = None;
continue;
} else {
lw += w_hwp;
}
}
}
}
let last_end = tokens
.last()
.map(|t| match t {
BreakToken::Text { end_idx, .. } => *end_idx,
BreakToken::DiscretionaryHyphen { idx, .. }
| BreakToken::Space { idx, .. }
| BreakToken::Tab { idx, .. }
| BreakToken::LineBreak { idx } => *idx + 1,
})
.unwrap_or(text_chars.len());
if line_start_idx <= last_end {
results.push(LineBreakResult {
start_idx: line_start_idx,
end_idx: last_end,
max_font_size: line_max_fs,
has_line_break: false,
});
}
if results.is_empty() {
results.push(LineBreakResult {
start_idx: initial_start_idx,
end_idx: text_chars.len(),
max_font_size: 0.0,
has_line_break: false,
});
}
results
}
fn recalc_width_hwp(tokens: &[BreakToken], current_token_idx: usize, new_line_start: usize) -> i32 {
let mut w = 0i32;
for t in &tokens[..current_token_idx] {
match t {
BreakToken::Text {
start_idx,
base_width,
..
} if *start_idx >= new_line_start => {
w += to_hwp(*base_width);
}
BreakToken::Space { idx, width, .. } if *idx >= new_line_start => {
w += to_hwp(*width);
}
_ => {}
}
}
w
}
fn recalc_space_savings_hwp(
tokens: &[BreakToken],
current_token_idx: usize,
new_line_start: usize,
condense_min_space: u8,
) -> i32 {
let mut w = 0i32;
let mut line_has_text = false;
for t in &tokens[..current_token_idx] {
match t {
BreakToken::Space {
idx, condense_base, ..
} if *idx >= new_line_start && line_has_text => {
w += condense_space_savings_hwp(to_hwp(*condense_base), condense_min_space);
}
BreakToken::Text { start_idx, .. } if *start_idx >= new_line_start => {
line_has_text = true;
}
_ => {}
}
}
w
}
fn forbidden_tail_before_oversized_run(
tokens: &[BreakToken],
text_chars: &[char],
break_token_idx: usize,
line_start_idx: usize,
line_width_hwp: i32,
) -> Option<usize> {
let BreakToken::Text {
start_idx, end_idx, ..
} = tokens.get(break_token_idx)?
else {
return None;
};
let mut tail = *end_idx;
while tail > *start_idx + 1 && is_line_start_forbidden(text_chars[tail - 1]) {
tail -= 1;
}
if tail == *end_idx {
return None;
}
let mut run_width_hwp = 0;
for token in &tokens[break_token_idx + 1..] {
let BreakToken::Text {
start_idx,
end_idx,
base_width,
..
} = token
else {
break;
};
if !text_chars[*start_idx..*end_idx]
.iter()
.all(char::is_ascii_graphic)
{
break;
}
run_width_hwp += to_hwp(*base_width);
}
if run_width_hwp <= line_width_hwp {
return None;
}
let head = tail - 1;
Some(if head > line_start_idx { head } else { tail })
}
fn first_token_at_or_after(tokens: &[BreakToken], boundary: usize) -> usize {
tokens.partition_point(|token| match token {
BreakToken::Text { end_idx, .. } => *end_idx <= boundary,
BreakToken::DiscretionaryHyphen { idx, .. }
| BreakToken::Space { idx, .. }
| BreakToken::Tab { idx, .. }
| BreakToken::LineBreak { idx } => *idx < boundary,
})
}
#[cfg(test)]
fn char_level_break_hwp(
text_chars: &[char],
token_start: usize,
token_end: usize,
line_start_idx: &mut usize,
mut lw: i32,
line_max_fs: f64,
first_line_w: i32,
normal_w: i32,
mut is_first_line: bool,
char_widths_hwp: &[i32], ) -> (Vec<LineBreakResult>, i32, f64) {
let mut results = Vec::new();
let mut current_w = if is_first_line {
first_line_w
} else {
normal_w
};
for ci in token_start..token_end {
let rel_idx = ci - token_start;
let char_w = if rel_idx < char_widths_hwp.len() {
char_widths_hwp[rel_idx]
} else {
let ch = text_chars[ci];
let char_w_px = if is_cjk_char(ch) {
line_max_fs.max(12.0)
} else {
line_max_fs.max(12.0) * 0.5
};
to_hwp(char_w_px)
};
if lw + char_w > current_w && ci > *line_start_idx {
results.push(LineBreakResult {
start_idx: *line_start_idx,
end_idx: ci,
max_font_size: line_max_fs,
has_line_break: false,
});
*line_start_idx = ci;
lw = char_w;
is_first_line = false;
current_w = normal_w;
} else {
lw += char_w;
}
}
(results, lw, line_max_fs)
}
fn paragraph_font_size_px(para: &Paragraph, styles: &ResolvedStyleSet) -> Option<f64> {
let largest = para
.char_shapes
.iter()
.filter_map(|cs| styles.char_styles.get(cs.char_shape_id as usize))
.map(|style| style.font_size)
.filter(|fs| *fs > 0.0)
.fold(None, |acc: Option<f64>, fs| {
Some(acc.map_or(fs, |a| a.max(fs)))
});
if largest.is_none() && explicit_zero_size_paragraph(para, styles) {
return Some(0.0);
}
largest
}
fn explicit_zero_size_paragraph(para: &Paragraph, styles: &ResolvedStyleSet) -> bool {
!para.char_shapes.is_empty()
&& para.char_shapes.iter().all(|cs| {
styles
.char_styles
.get(cs.char_shape_id as usize)
.is_some_and(|style| style.font_size == 0.0)
})
}
pub(crate) fn paragraph_end_font_size_px(para: &Paragraph, styles: &ResolvedStyleSet) -> f64 {
let Some(end_pos) = para.char_count.checked_sub(1) else {
return 0.0;
};
let id = find_active_char_shape(¶.char_shapes, end_pos);
styles
.char_styles
.get(id as usize)
.map(|style| style.font_size)
.unwrap_or(0.0)
}
fn floating_anchor_char_font_sizes(
para: &Paragraph,
styles: &ResolvedStyleSet,
) -> Vec<(usize, f64)> {
match floating_anchor_char_font_sizes_with_storage(para, styles, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn floating_anchor_char_font_sizes_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
storage: &S,
) -> Result<Vec<(usize, f64)>, S::Error> {
Ok({
if para.controls.is_empty() || para.char_shapes.is_empty() {
return Ok(Vec::new());
}
let text_positions = para.try_control_text_positions(storage)?;
let utf16_positions = para.control_utf16_positions_with_storage(storage)?;
storage.collect(
para.controls
.iter()
.zip(text_positions)
.zip(utf16_positions)
.filter(|((ctrl, _), _)| match ctrl {
Control::Table(table) => !table.common.treat_as_char,
Control::Picture(pic) => !pic.common.treat_as_char,
Control::Shape(shape) => !shape.common().treat_as_char,
_ => false,
})
.filter_map(|((_, text_pos), utf16_pos)| {
let id = find_active_char_shape(¶.char_shapes, utf16_pos);
styles
.char_styles
.get(id as usize)
.map(|style| style.font_size)
.filter(|fs| *fs > 0.0)
.map(|fs| (text_pos, fs))
}),
)?
})
}
fn floating_anchor_font_size_px(
anchors: &[(usize, f64)],
range: Range<usize>,
is_last_line: bool,
text_len: usize,
) -> f64 {
anchors
.iter()
.filter(|(pos, _)| range.contains(pos) || (is_last_line && *pos == text_len))
.map(|(_, fs)| *fs)
.fold(0.0, f64::max)
}
fn tac_shape_box_hu(shape: &crate::model::shape::ShapeObject) -> (i32, i32) {
let common = shape.common();
let margin = &common.margin;
(
shape.flow_width_hu() + i32::from(margin.left) + i32::from(margin.right),
shape.flow_height_hu() + i32::from(margin.top) + i32::from(margin.bottom),
)
}
fn inline_control_line_height_hwp(para: &Paragraph) -> Option<i32> {
para.controls
.iter()
.filter_map(|ctrl| match ctrl {
Control::Picture(pic) if pic.common.treat_as_char => {
Some(super::inline_picture_occupied_size_hu(pic).1)
}
Control::Shape(shape) if shape.common().treat_as_char => {
Some(tac_shape_box_hu(shape).1)
}
Control::Table(table) if table.common.treat_as_char => Some(table.common.height as i32),
Control::Equation(eq) if eq.common.treat_as_char => {
Some(crate::renderer::equation::flow_height_hwp(eq) as i32)
}
Control::Form(form) if form.common.treat_as_char => Some(form.height as i32),
_ => None,
})
.filter(|height| *height > 0)
.max()
}
fn inline_control_size_hwp(ctrl: &Control) -> Option<(i32, i32)> {
match inline_control_size_hwp_with_storage(ctrl, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn inline_control_size_hwp_with_storage<S: crate::storage::Storage>(
ctrl: &Control,
storage: &S,
) -> Result<Option<(i32, i32)>, S::Error> {
Ok({
let (width, height) = match ctrl {
Control::Picture(pic) if pic.common.treat_as_char => {
super::inline_picture_occupied_size_hu(pic)
}
Control::Shape(shape) if shape.common().treat_as_char => tac_shape_box_hu(shape),
Control::Table(table) if table.common.treat_as_char => {
let width = table.flow_width_hu_with_storage(storage)? as i32;
(width, table.common.height as i32)
}
Control::Equation(eq) if eq.common.treat_as_char => (
crate::renderer::equation::inline_box::horizontal_metrics(eq).occupied_width_hwp(),
crate::renderer::equation::flow_height_hwp(eq) as i32,
),
Control::Form(form) if form.common.treat_as_char => {
(form.width as i32, form.height as i32)
}
_ => return Ok(None),
};
if width > 0 && height > 0 {
Some((width, height))
} else {
None
}
})
}
fn inline_control_occupied_size_hwp(
control: &Control,
styles: &ResolvedStyleSet,
dpi: f64,
) -> Option<(i32, i32)> {
match inline_control_occupied_size_hwp_with_storage(
control,
styles,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn inline_control_occupied_size_hwp_with_storage<S: crate::storage::Storage>(
control: &Control,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<Option<(i32, i32)>, S::Error> {
Ok({
if let Control::Table(table) = control {
if let Some(measured) =
super::measured_reflow_inline_table_with_storage(table, styles, dpi, storage)?
{
let Some(width) = i32::try_from(table.flow_width_hu_with_storage(storage)?)
.ok()
.map(|width| {
width
.saturating_add(i32::from(table.outer_margin_left))
.saturating_add(i32::from(table.outer_margin_right))
})
else {
return Ok(None);
};
let height = px_to_hwpunit(measured.total_height, dpi)
.saturating_add(i32::from(table.outer_margin_top))
.saturating_add(i32::from(table.outer_margin_bottom));
return Ok((width > 0 && height > 0).then_some((width, height)));
}
}
let Some((mut width, mut height)) = inline_control_size_hwp_with_storage(control, storage)?
else {
return Ok(None);
};
if let Control::Table(table) = control {
let measured = crate::renderer::height_measurer::HeightMeasurer::new(dpi)
.with_session_edited(true)
.measure_table_with_storage(table, 0, 0, styles, storage)?;
let measured_hu = (measured.total_height * 7200.0 / dpi).round() as i32;
if measured_hu > 0 {
height = measured_hu;
}
width = width
.saturating_add(i32::from(table.outer_margin_left))
.saturating_add(i32::from(table.outer_margin_right));
height = height
.saturating_add(i32::from(table.outer_margin_top))
.saturating_add(i32::from(table.outer_margin_bottom));
}
Some((width, height))
})
}
fn inline_control_spacing_height_hwp(control: &Control) -> Option<i32> {
match control {
Control::Equation(equation)
if equation.common.treat_as_char && equation.common.affect_line_spacing =>
{
Some(crate::renderer::equation::flow_height_hwp(equation) as i32)
}
_ => None,
}
}
fn flow_inline_controls_with_tac_tables(
para: &Paragraph,
styles: &ResolvedStyleSet,
dpi: f64,
) -> Vec<FlowInlineControl> {
match flow_inline_controls_with_tac_tables_with_storage(
para,
styles,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn flow_inline_controls_with_tac_tables_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<Vec<FlowInlineControl>, S::Error> {
Ok({
let text_len = para.text.chars().count();
let mut controls = flow_inline_controls_with_storage(para, styles, storage)?;
for ((control, char_position), utf16_position) in para
.controls
.iter()
.zip(para.try_control_text_positions(storage)?)
.zip(para.control_utf16_positions_with_storage(storage)?)
{
let Control::Table(table) = control else {
continue;
};
if !table.common.treat_as_char || char_position >= text_len {
continue;
}
let Some((width_hwp, height_hwp)) =
inline_control_occupied_size_hwp_with_storage(control, styles, dpi, storage)?
else {
continue;
};
storage.push(
&mut controls,
FlowInlineControl {
char_position,
utf16_position,
width_hwp,
height_hwp,
baseline_distance_hwp: None,
spacing_height_hwp: inline_control_spacing_height_hwp(control),
},
)?;
}
storage.bytes(std::mem::size_of_val(controls.as_slice()))?;
controls.sort_by_key(|control| control.char_position);
controls
})
}
#[path = "inline_control_flow.rs"]
mod inline_control_flow;
use inline_control_flow::{flow_inline_controls, flow_inline_controls_with_storage};
fn flow_inline_baseline_hwp(control: &Control, _height_hwp: i32) -> Option<i32> {
match control {
Control::Equation(equation) => {
let baseline = crate::renderer::equation::flow_metrics_hwp(equation).2;
(baseline > 0).then_some(baseline)
}
_ => None,
}
}
pub(crate) fn control_is_width_neutral_marker(control: &Control) -> bool {
inline_control_size_hwp(control).is_none() && !control_owns_a_layout_box(control)
}
fn control_owns_a_layout_box(control: &Control) -> bool {
matches!(
control,
Control::Table(_)
| Control::Shape(_)
| Control::Picture(_)
| Control::Equation(_)
| Control::Form(_)
| Control::Header(_)
| Control::Footer(_)
| Control::Footnote(_)
| Control::Endnote(_)
)
}
fn control_is_line_width_neutral_float_table(control: &Control) -> bool {
matches!(control, Control::Table(t)
if !t.common.treat_as_char
&& matches!(t.common.text_wrap, crate::model::shape::TextWrap::TopAndBottom))
}
pub(crate) fn control_is_line_width_neutral_float_object(control: &Control) -> bool {
use crate::model::shape::TextWrap;
let common = match control {
Control::Picture(picture) => &picture.common,
Control::Shape(shape) => shape.common(),
_ => return false,
};
!common.treat_as_char
&& matches!(
common.text_wrap,
TextWrap::TopAndBottom | TextWrap::BehindText | TextWrap::InFrontOfText
)
}
pub(crate) fn control_is_square_float_object(control: &Control) -> bool {
let common = match control {
Control::Picture(picture) => &picture.common,
Control::Shape(shape) => shape.common(),
_ => return false,
};
!common.treat_as_char && matches!(common.text_wrap, crate::model::shape::TextWrap::Square)
}
pub(crate) fn control_owns_body_band(control: &Control) -> bool {
match control {
Control::Picture(picture) => !picture.common.treat_as_char,
Control::Shape(shape) => {
crate::renderer::float_placement::shape_wraps_beside_text(shape.common())
}
_ => false,
}
}
pub(crate) fn row_is_carved_from_box(
column_start: i32,
segment_width: i32,
paragraph_box: &Range<i32>,
) -> bool {
const BOX_TOLERANCE_HU: u32 = 200;
segment_width > 0
&& (column_start.abs_diff(paragraph_box.start) > BOX_TOLERANCE_HU
|| column_start
.saturating_add(segment_width)
.abs_diff(paragraph_box.end)
> BOX_TOLERANCE_HU)
}
pub(crate) fn control_is_float_shape_beside_text(control: &Control) -> bool {
matches!(control, Control::Shape(shape)
if crate::renderer::float_placement::shape_wraps_beside_text(shape.common()))
}
pub(super) fn remeasured_equation_start_row(para: &Paragraph) -> Option<usize> {
let positions = super::find_render_inline_control_positions(para);
para.controls
.iter()
.enumerate()
.filter_map(|(index, control)| {
let Control::Equation(equation) = control else {
return None;
};
if !equation.common.treat_as_char
|| (crate::renderer::equation::flow_width_hwp(equation) == equation.common.width
&& !crate::renderer::equation::current_simple_math_advance_was_remeasured(
equation,
))
{
return None;
}
let position = *positions.get(index)?;
let chars = para.text.chars().count();
para.line_segs
.iter()
.enumerate()
.rev()
.find_map(|(row, _)| {
let (start, _) = super::utf16_range_to_text_range(
¶.char_offsets,
para.line_seg_text_start(row),
u32::MAX,
chars,
);
(start <= position).then_some(row)
})
})
.min()
}
pub(super) fn supports_overlay_table_frame_controls(para: &Paragraph) -> bool {
let is_overlay = |common: &crate::model::shape::CommonObjAttr| {
!common.treat_as_char
&& matches!(
common.text_wrap,
crate::model::shape::TextWrap::InFrontOfText
| crate::model::shape::TextWrap::BehindText
)
};
let mut overlay_tables = 0usize;
for control in ¶.controls {
match control {
Control::Table(table) if is_overlay(&table.common) => {
overlay_tables += 1;
}
Control::Picture(pic) if is_overlay(&pic.common) => {}
Control::Shape(shape) if is_overlay(shape.common()) => {}
other if control_is_width_neutral_marker(other) => {}
_ => return false,
}
}
overlay_tables > 0
}
pub(super) fn supports_overlay_shape_frame_controls(para: &Paragraph) -> bool {
let is_overlay = |common: &crate::model::shape::CommonObjAttr| {
!common.treat_as_char
&& matches!(
common.text_wrap,
crate::model::shape::TextWrap::InFrontOfText
| crate::model::shape::TextWrap::BehindText
)
};
if !para.line_segs.is_empty() {
return false;
}
let mut overlay_objects = 0usize;
for control in ¶.controls {
match control {
Control::Picture(pic) if is_overlay(&pic.common) => overlay_objects += 1,
Control::Shape(shape) if is_overlay(shape.common()) => overlay_objects += 1,
other if control_is_width_neutral_marker(other) => {}
_ => return false,
}
}
overlay_objects > 0
}
pub(super) fn supports_cached_body_frame_controls(para: &Paragraph) -> bool {
let remeasured = remeasured_equation_start_row(para).is_some();
para.controls.iter().all(|control| {
control_is_width_neutral_marker(control)
|| control_is_line_width_neutral_float_table(control)
|| (crate::renderer::para_has_no_stored_line_segs(para)
&& crate::model::border_paint::is_cell_frame_paint(control))
|| (remeasured && matches!(control, Control::Equation(eq) if eq.common.treat_as_char))
|| (remeasured && matches!(control, Control::Footnote(_)))
})
}
pub(super) fn supports_tac_table_band_frame_controls(para: &Paragraph) -> bool {
let mut tac_tables = 0usize;
for control in ¶.controls {
match control {
Control::Table(table) if table.common.treat_as_char => tac_tables += 1,
Control::Picture(picture) if picture.common.treat_as_char => {}
Control::Equation(equation) if equation.common.treat_as_char => {}
Control::Header(_) | Control::Footer(_) => {}
other if control_is_width_neutral_marker(other) => {}
_ => return false,
}
}
tac_tables == 1 || (tac_tables > 1 && crate::renderer::para_has_no_stored_line_segs(para))
}
pub(crate) fn supports_picture_band_frame_controls(para: &Paragraph) -> bool {
let mut non_tac_pictures = 0usize;
for control in ¶.controls {
match control {
Control::Picture(picture) if !picture.common.treat_as_char => {
non_tac_pictures += 1;
}
square if control_is_square_float_object(square) => {
non_tac_pictures += 1;
}
Control::Picture(picture) if picture.common.treat_as_char => {}
Control::Equation(equation) if equation.common.treat_as_char => {}
other if control_is_width_neutral_marker(other) => {}
_ => return false,
}
}
non_tac_pictures <= 1
}
fn no_ls_inline_picture_host_fill(para: &Paragraph) -> bool {
para.line_segs.is_empty() && supports_inline_picture_frame_controls(para)
}
fn supports_inline_picture_frame_controls(para: &Paragraph) -> bool {
para.controls
.iter()
.any(|control| matches!(control, Control::Picture(picture) if picture.common.treat_as_char))
&& para.controls.iter().all(|control| match control {
Control::Picture(picture) if picture.common.treat_as_char => picture.caption.is_none(),
float if control_is_line_width_neutral_float_object(float) => true,
shape if control_is_float_shape_beside_text(shape) => true,
Control::Picture(_) => false,
other => control_is_width_neutral_marker(other),
})
}
pub(super) fn supports_inline_form_frame_controls(para: &Paragraph) -> bool {
para.controls
.iter()
.any(|control| matches!(control, Control::Form(form) if form.common.treat_as_char))
&& para.controls.iter().all(|control| match control {
Control::Form(form) => form.common.treat_as_char,
other => control_is_width_neutral_marker(other),
})
}
fn field_led_leading_control(
para: &Paragraph,
occupied_controls: &[(usize, u32, i32, i32)],
) -> Option<(usize, u32, i32, i32)> {
let mut leading = occupied_controls
.iter()
.copied()
.filter(|(position, _, _, _)| *position == 0);
let candidate = leading.next()?;
if leading.next().is_some() {
return None;
}
let field_before = para
.controls
.iter()
.zip(para.control_utf16_positions())
.any(|(control, start)| matches!(control, Control::Field(_)) && start < candidate.1);
field_before.then_some(candidate)
}
fn inline_control_requires_own_line(
para: &Paragraph,
occupied_controls: &[(usize, u32, i32, i32)],
text_chars: &[char],
line_breaks: &[LineBreakResult],
available_width_px: f64,
indent_px: f64,
reflow_is_first_line: bool,
styles: &ResolvedStyleSet,
space_metric: SpaceMetric,
) -> Option<(usize, u32, i32, bool)> {
let text_len = para.text.chars().count();
let mut candidates = occupied_controls
.iter()
.copied()
.filter(|(position, _, _, _)| *position > 0 && *position <= text_len);
let (position, utf16_start, control_width, height) = match candidates.next() {
Some(candidate) => {
if candidates.next().is_some() {
return None;
}
candidate
}
None => field_led_leading_control(para, occupied_controls)?,
};
let (line_idx, line) = line_breaks
.iter()
.enumerate()
.find(|(_, line)| line.start_idx == position)
.or_else(|| {
line_breaks
.iter()
.enumerate()
.rfind(|(_, line)| line.start_idx < position && position <= line.end_idx)
})?;
let is_first_line = reflow_is_first_line && line_idx == 0;
let available_hwp = if indent_px > 0.0 && is_first_line {
to_hwp((available_width_px - indent_px).max(1.0))
} else if indent_px < 0.0 && !is_first_line {
to_hwp((available_width_px + indent_px).max(1.0))
} else {
to_hwp(available_width_px)
};
let scope = ParagraphMetricScope::new(text_chars, styles)
.with_space_metric(space_metric)
.with_literal_figure_spaces(¶.literal_figure_spaces);
let width_of = |range: Range<usize>| {
let text: String = text_chars[range.clone()].iter().collect();
to_hwp(measure_token_width(
&scope,
&text,
range.start,
¶.char_offsets,
¶.char_shapes,
styles,
0,
&[],
))
};
let prefix_width = width_of(line.start_idx..position);
let tolerance_hwp = line_break_tolerance_hwp(available_hwp);
if control_width <= available_hwp + tolerance_hwp
&& prefix_width + control_width <= available_hwp + tolerance_hwp
{
return None;
}
let row_hwp = if indent_px < 0.0 {
to_hwp((available_width_px + indent_px).max(1.0))
} else {
to_hwp(available_width_px)
};
let suffix_end = (position..line.end_idx)
.rfind(|&i| !text_chars[i].is_whitespace())
.map_or(position, |i| i + 1);
let suffix_row = suffix_end > position
&& control_width + width_of(position..suffix_end)
> row_hwp + line_break_tolerance_hwp(row_hwp);
Some((position, utf16_start, height, suffix_row))
}
fn char_index_to_utf16_offset(para: &Paragraph, char_index: usize) -> u32 {
if let Some(offset) = para.char_offsets.get(char_index) {
return *offset;
}
para.char_offsets
.last()
.zip(para.text.chars().last())
.map(|(offset, ch)| *offset + Paragraph::char_stream_len(ch))
.unwrap_or_else(|| {
para.text
.chars()
.take(char_index)
.map(Paragraph::char_stream_len)
.sum()
})
}
fn line_start_utf16_offset(
para: &Paragraph,
char_index: usize,
inline_controls: &[FlowInlineControl],
) -> u32 {
let end = (char_index > 0 && char_index == para.char_offsets.len())
.then(|| para.char_offsets[char_index - 1])
.filter(|&raw| {
inline_controls.iter().any(|control| {
control.char_position == char_index - 1 && control.utf16_position == raw
})
})
.map_or_else(
|| char_index_to_utf16_offset(para, char_index),
|raw| raw + CTRL_CHAR_CODE_UNITS,
);
inline_controls
.iter()
.filter(|control| control.char_position == char_index)
.map(|control| control.utf16_position)
.fold(end, u32::min)
}
pub(super) fn baseline_distance_hwp(line_height_hwp: i32) -> i32 {
(line_height_hwp as f64 * 0.85).round() as i32
}
pub(super) fn publish_vertical_alignment_baselines(
para: &mut Paragraph,
styles: &ResolvedStyleSet,
) {
let alignment = styles
.para_styles
.get(para.para_shape_id as usize)
.map_or(0, |style| style.vertical_alignment);
if alignment == 0 {
return;
}
for row in &mut para.line_segs {
row.baseline_distance = match alignment {
1 => 0,
2 => row.text_height / 2,
_ => row.text_height,
};
}
}
fn apply_reflowed_equation_row_metrics(
para: &Paragraph,
segments: &mut [LineSeg],
styles: &ResolvedStyleSet,
spacing_type: LineSpacingType,
spacing_value: f64,
dpi: f64,
) {
let mut equations = vec![Vec::new(); segments.len()];
for (ci, control) in para.controls.iter().enumerate() {
let Control::Equation(equation) = control else {
continue;
};
if !equation.common.treat_as_char {
continue;
}
if let Some(line) = super::control_slot_line_index_with_starts(
para,
ci,
segments.iter().map(|seg| seg.text_start),
) {
equations[line].push(equation.as_ref());
}
}
let chars: Vec<_> = para.text.chars().collect();
for line in 0..segments.len() {
if equations[line].is_empty() {
continue;
}
let start = segments[line].text_start;
let end = segments
.get(line + 1)
.map_or(u32::MAX, |seg| seg.text_start);
let mut text_baseline = 0;
let mut spacing_height = 0;
for (index, ch) in chars.iter().enumerate() {
let offset = char_index_to_utf16_offset(para, index);
if offset < start || offset >= end || *ch == '\u{fffc}' {
continue;
}
let shape = find_active_char_shape(¶.char_shapes, offset);
let height = font_size_to_line_height(token_line_font_size(styles, shape), dpi);
spacing_height = spacing_height.max(height);
if ch.is_whitespace() || ch.is_control() {
continue;
}
text_baseline = text_baseline.max(baseline_distance_hwp(height));
}
if spacing_height == 0 {
spacing_height =
font_size_to_line_height(paragraph_font_size_px(para, styles).unwrap_or(12.0), dpi);
}
let mut equation_baseline = 0;
let mut affects_spacing = false;
let seg = &mut segments[line];
for equation in &equations[line] {
let (_, height, baseline) = crate::renderer::equation::flow_metrics_hwp(equation);
let height = height as i32;
seg.line_height = seg.line_height.max(height);
seg.text_height = seg.text_height.max(height);
equation_baseline = equation_baseline.max(baseline);
if equation.common.affect_line_spacing {
affects_spacing = true;
spacing_height = spacing_height.max(height);
}
}
if equation_baseline > 0 {
seg.baseline_distance = text_baseline.max(equation_baseline);
}
if affects_spacing {
seg.line_spacing =
compute_line_spacing_hwp(spacing_type, spacing_value, spacing_height, dpi);
}
}
}
pub(super) fn apply_inline_control_line_height(seg: &mut LineSeg, height_hwp: i32) {
if height_hwp > seg.line_height {
seg.line_height = height_hwp;
seg.text_height = height_hwp;
seg.baseline_distance = baseline_distance_hwp(height_hwp);
}
}
fn apply_inline_control_frame_height(metrics: &mut FrameRowMetrics, height_hwp: i32) {
if height_hwp > metrics.line_height {
metrics.line_height = height_hwp;
metrics.text_height = height_hwp;
metrics.baseline_distance = baseline_distance_hwp(height_hwp);
}
}
pub(crate) fn frame_metrics_for_line(
max_font_size: f64,
fallback_font_size: f64,
line_spacing_type: LineSpacingType,
line_spacing_value: f64,
dpi: f64,
) -> FrameRowMetrics {
let font_size = if max_font_size > 0.0 {
max_font_size
} else {
fallback_font_size
};
let line_height = font_size_to_line_height(font_size, dpi).max(1);
FrameRowMetrics {
vertical_pos: 0,
line_height,
text_height: line_height,
baseline_distance: baseline_distance_hwp(line_height),
line_spacing: compute_line_spacing_hwp(
line_spacing_type,
line_spacing_value,
line_height,
dpi,
),
}
}
fn mark_indented_lines(
lines: &mut [LineSeg],
first_line_index: usize,
para_style: Option<&ResolvedParaStyle>,
stored: &[LineSeg],
line_width_hwp: i32,
) {
stamp_indentation(
lines,
first_line_index,
reflow_indentation_pattern(para_style, stored, line_width_hwp),
);
stamp_paragraph_head(lines, first_line_index, para_style);
}
fn stamp_paragraph_head(
lines: &mut [LineSeg],
first_line_index: usize,
para_style: Option<&ResolvedParaStyle>,
) {
let head = paragraph_has_head(para_style);
for (line_index, line) in (first_line_index..).zip(lines.iter_mut()) {
if head && line_index == 0 {
line.tag |= LineSeg::TAG_PARAGRAPH_HEAD;
} else {
line.tag &= !LineSeg::TAG_PARAGRAPH_HEAD;
}
}
}
fn paragraph_has_head(para_style: Option<&ResolvedParaStyle>) -> bool {
para_style.is_some_and(|style| style.head_type != HeadType::None)
}
fn reflow_indentation_pattern(
para_style: Option<&ResolvedParaStyle>,
stored: &[LineSeg],
line_width_hwp: i32,
) -> (bool, bool) {
let indent = para_style.map_or(0.0, |style| style.indent);
let indented = |line: &LineSeg| line.tag & LineSeg::TAG_INDENTATION != 0;
let hancom_record = !stored.is_empty()
&& stored
.iter()
.all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
if hancom_record
&& (indent > 0.0 || (indent < 0.0 && stored.len() > 1))
&& !stored.iter().any(indented)
{
(false, false)
} else if indent == 0.0 && para_style.is_some_and(|style| style.head_type != HeadType::None) {
(false, hancom_record && stored.iter().skip(1).any(indented))
} else if !indent_leaves_line_room_hwp(to_hwp(indent), line_width_hwp) {
(false, false)
} else {
(indent > 0.0, indent < 0.0)
}
}
pub(crate) fn restamp_indentation(lines: &mut [LineSeg], old_indent: i32, new_indent: i32) {
if old_indent != new_indent {
stamp_indentation(lines, 0, (new_indent > 0, new_indent < 0));
}
}
fn stamp_indentation(lines: &mut [LineSeg], first_line_index: usize, (first, rest): (bool, bool)) {
for (line_index, line) in (first_line_index..).zip(lines.iter_mut()) {
if (line_index == 0 && first) || (line_index > 0 && rest) {
line.tag |= LineSeg::TAG_INDENTATION;
} else {
line.tag &= !LineSeg::TAG_INDENTATION;
}
}
}
fn apply_resolved_field_tokens(
para: &Paragraph,
styles: &ResolvedStyleSet,
inline: &[FlowInlineControl],
tokens: &mut Vec<BreakToken>,
) {
match apply_resolved_field_tokens_with_storage(
para,
styles,
inline,
tokens,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
fn apply_resolved_field_tokens_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
styles: &ResolvedStyleSet,
inline: &[FlowInlineControl],
tokens: &mut Vec<BreakToken>,
storage: &S,
) -> Result<(), S::Error> {
{
if para.layout_field_values.is_empty() {
return Ok(());
}
let mut resolved = Vec::new();
for token in tokens.drain(..) {
let field = match &token {
BreakToken::Space { idx, .. } => Some(*idx),
BreakToken::Text {
start_idx, end_idx, ..
} if *end_idx == *start_idx + 1 => Some(*start_idx),
_ => None,
}
.and_then(|position| {
super::resolved_fields::token_width(para, position, styles).map(|(width, size)| {
(
position,
width + inline_width_px_at(inline, position, styles),
size,
)
})
});
if let Some((position, width, size)) = field {
storage.push(
&mut resolved,
BreakToken::Text {
start_idx: position,
end_idx: position + 1,
base_width: width,
width,
max_font_size: size,
base_char_widths: storage.collect([width])?,
char_widths: storage.collect([width])?,
},
)?;
} else {
storage.push(&mut resolved, token)?;
}
}
*tokens = resolved;
};
Ok(())
}
pub(crate) fn layout_paragraph_in_frame(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
) -> Option<Vec<LineSeg>> {
layout_paragraph_in_frame_impl(para, frame, styles, dpi, true, 0, FramePurpose::Body)
}
pub(crate) fn layout_paragraph_in_frame_with_storage<S: Storage>(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<Option<Vec<LineSeg>>, S::Error> {
try_layout_paragraph_in_frame_impl(
para,
frame,
styles,
dpi,
true,
FrameStart::Scalar(0),
FramePurpose::Body,
storage,
)
}
pub(crate) fn layout_picture_anchor_in_frame(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
) -> Option<Vec<LineSeg>> {
layout_paragraph_in_frame_impl(
para,
frame,
styles,
dpi,
true,
0,
FramePurpose::PictureAnchor,
)
}
fn layout_paragraph_in_frame_impl(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
allow_kerning: bool,
start_char: usize,
purpose: FramePurpose,
) -> Option<Vec<LineSeg>> {
match try_layout_paragraph_in_frame_impl(
para,
frame,
styles,
dpi,
allow_kerning,
FrameStart::Scalar(start_char),
purpose,
&Unbounded,
) {
Ok(lines) => lines,
Err(never) => match never {},
}
}
#[derive(Clone, Copy)]
enum FrameStart {
Scalar(usize),
SourceUtf16(u32),
}
const UNBROKEN_LINE_WIDTH_PX: f64 = 1.0e6;
fn try_layout_paragraph_in_frame_impl<S: Storage>(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
allow_kerning: bool,
start: FrameStart,
purpose: FramePurpose,
storage: &S,
) -> Result<Option<Vec<LineSeg>>, S::Error> {
let supported = match purpose {
FramePurpose::Body => {
supports_picture_band_frame_controls(para)
|| supports_cached_body_frame_controls(para)
|| supports_inline_form_frame_controls(para)
|| (para.line_segs.is_empty() && supports_tac_table_band_frame_controls(para))
|| (para.line_segs.is_empty() && supports_overlay_table_frame_controls(para))
|| supports_overlay_shape_frame_controls(para)
|| no_ls_inline_picture_host_fill(para)
}
FramePurpose::PictureAnchor => picture_anchor_projection::admits(para),
};
if !supported {
return Ok(None);
}
let source_start_utf16 = match start {
FrameStart::Scalar(0) => 0,
FrameStart::Scalar(index) => char_index_to_utf16_offset(para, index),
FrameStart::SourceUtf16(offset) => offset,
};
let projected = if (para.line_segs.is_empty()
&& (supports_tac_table_band_frame_controls(para)
|| supports_inline_form_frame_controls(para)))
|| no_ls_inline_picture_host_fill(para)
|| remeasured_equation_start_row(para).is_some()
{
inline_frame_input::project_with_storage(para, styles, dpi, storage)?
} else {
None
};
let para = projected.as_ref().map_or(para, |(input, _)| input);
let start_char = match (start, projected.as_ref()) {
(FrameStart::Scalar(index), None) => index,
_ => para
.char_offsets
.partition_point(|offset| *offset < source_start_utf16),
};
let mut text_chars = storage.collect(para.text.chars())?;
for (position, _) in ¶.layout_field_values {
if let Some(character) = text_chars.get_mut(*position) {
*character = '\u{0015}';
}
}
let paragraph_end_font_size = para
.char_shapes
.iter()
.find(|shape| shape.start_pos == para.char_count.saturating_sub(1))
.and_then(|shape| styles.char_styles.get(shape.char_shape_id as usize))
.map_or(0.0, |style| style.font_size);
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let frame_width_hwp = frame.horizontal.end.saturating_sub(frame.horizontal.start);
let indentation_pattern =
reflow_indentation_pattern(para_style, ¶.line_segs, frame_width_hwp);
let indent_px = if indentation_pattern == (false, false) {
0.0
} else {
para_style.map_or(0.0, |style| style.indent)
};
let (marker_hang_px, indent_px) = list_marker_breaker_box(para, styles, indent_px);
let marker_font_size = list_marker_metrics::include_marker(para, styles, true, 0.0);
let mut tab_fill = TabFill::for_paragraph(
para_style,
indent_px,
crate::renderer::hwpunit_to_px(
frame.horizontal.end.saturating_sub(frame.horizontal.start),
dpi,
),
);
tab_fill.default_width_px = styles.default_tab_width(tab_fill.default_width_px);
tab_fill.stop_overflow_wraps = !styles.word_compat_target;
let english_break_unit = para_style
.map(|style| style.english_break_unit)
.unwrap_or(0);
let korean_break_unit = para_style.map(|style| style.korean_break_unit).unwrap_or(0);
let condense_min_space = para_style
.map(|style| style.condense_min_space)
.unwrap_or(0);
let line_spacing_type = para_style
.map(|style| style.line_spacing_type)
.unwrap_or(LineSpacingType::Percent);
let line_spacing_value = para_style.map(|style| style.line_spacing).unwrap_or(160.0);
let mut inline_controls = if let Some((_, controls)) = projected.as_ref() {
storage.copy_slice(controls)?
} else if para.line_segs.is_empty() && supports_tac_table_band_frame_controls(para) {
flow_inline_controls_with_tac_tables_with_storage(para, styles, dpi, storage)?
} else {
flow_inline_controls_with_storage(para, styles, storage)?
};
if purpose == FramePurpose::PictureAnchor {
let prefix = crate::renderer::layout::leading_endnote_prefix_geometry(para, styles, 0);
if prefix.advance > 0.0 && prefix.height > 0.0 {
if std::env::var_os("RHWP_PICTURE_ANCHOR_DEBUG").is_some() {
eprintln!(
"PICTURE_ANCHOR_PREFIX advance={:.4} height={:.4} baseline={:.4}",
prefix.advance, prefix.height, prefix.baseline,
);
}
storage.reserve(&mut inline_controls, 1)?;
inline_controls.push(FlowInlineControl {
char_position: 0,
utf16_position: 0,
width_hwp: px_to_hwpunit(prefix.advance, dpi),
height_hwp: px_to_hwpunit(prefix.height, dpi),
baseline_distance_hwp: Some(px_to_hwpunit(prefix.baseline, dpi)),
spacing_height_hwp: None,
});
storage.bytes(std::mem::size_of_val(inline_controls.as_slice()))?;
inline_controls.sort_by_key(|control| control.char_position);
}
}
let space_metric =
if super::missing_lineseg_indented_cell_has_uniform_metrics_with_tracking(para, styles) {
SpaceMetric::HalfCell
} else if frame.kopub_justified_space
&& para_style.is_some_and(|style| style.alignment == Alignment::Justify)
{
SpaceMetric::KoPubJustified
} else {
SpaceMetric::Stored
};
let mut tokens = try_tokenize_paragraph_with_regenerated_space_metric(
&text_chars,
¶.char_offsets,
¶.char_shapes,
styles,
english_break_unit,
korean_break_unit,
space_metric,
&inline_controls,
para.control_mask & (1 << 0x18) != 0,
¶.literal_figure_spaces,
storage,
)?;
apply_resolved_field_tokens_with_storage(para, styles, &inline_controls, &mut tokens, storage)?;
apply_auto_left_tab_targets(&mut tokens, para_style);
let prepared_kerning = allow_kerning
.then(|| {
prepare_paragraph_kerning(para, &text_chars, styles, space_metric, &inline_controls)
})
.flatten()
.and_then(|prepared| {
apply_paragraph_kerning_to_tokens(&mut tokens, &prepared.measurement).map(|_| prepared)
});
let mut kerning_transaction = prepared_kerning
.as_ref()
.map(|prepared| prepared.context.layout_session());
let mut kerning_break_session = prepared_kerning.as_ref().and_then(|prepared| {
crate::renderer::kerning::KerningParagraphBreakSession::new(
¶.text,
&prepared.scalar_styles,
&prepared.hard_boundaries,
&prepared.measurement,
kerning_transaction.as_mut()?,
)
.ok()
});
let terminal_tokens = (space_metric == SpaceMetric::HalfCell
&& prepared_kerning.is_none()
&& para_style
.is_some_and(|style| style.alignment == crate::model::style::Alignment::Justify))
.then(|| {
let mut tokens = try_tokenize_paragraph_with_regenerated_space_metric(
&text_chars,
¶.char_offsets,
¶.char_shapes,
styles,
english_break_unit,
korean_break_unit,
SpaceMetric::Stored,
&inline_controls,
para.control_mask & (1 << 0x18) != 0,
¶.literal_figure_spaces,
storage,
)?;
apply_resolved_field_tokens_with_storage(
para,
styles,
&inline_controls,
&mut tokens,
storage,
)?;
apply_auto_left_tab_targets(&mut tokens, para_style);
Ok(tokens)
})
.transpose()?;
let mut letter_spacing_px =
try_resolved_paragraph_letter_spacing(para, &text_chars, styles, space_metric, storage)?;
if projected.is_some() {
for control in &inline_controls {
letter_spacing_px[control.char_position] = 0.0;
}
}
let zero_size_paragraph = explicit_zero_size_paragraph(para, styles);
let fallback_font_size = if para.text.is_empty() {
para.char_shapes
.first()
.and_then(|char_shape| styles.char_styles.get(char_shape.char_shape_id as usize))
.map(|style| style.font_size)
.unwrap_or(12.0)
} else if zero_size_paragraph {
0.0
} else {
12.0
};
let terminal_inline_metrics = inline_controls
.is_empty()
.then(|| {
let height_hwp = inline_control_line_height_hwp(para)?;
let baseline_distance_hwp = para
.controls
.iter()
.filter_map(|control| match control {
Control::Equation(equation)
if equation.common.treat_as_char
&& crate::renderer::equation::flow_height_hwp(equation) as i32
== height_hwp
&& equation.baseline > 0 =>
{
Some(crate::renderer::equation::flow_metrics_hwp(equation).2)
}
_ => None,
})
.max();
Some((height_hwp, baseline_distance_hwp))
})
.flatten();
let terminal_inline_spacing_height = terminal_inline_metrics.and_then(|_| {
para.controls
.iter()
.filter_map(inline_control_spacing_height_hwp)
.max()
});
let source_tag = para
.line_segs
.first()
.map(|segment| segment.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY)
.unwrap_or(LineSeg::TAG_IMPLEMENTATION_PROPERTY);
let first_row = frame.row_count();
let frame_checkpoint = frame.try_append_checkpoint(storage)?;
let mut cursor = FillCursor::replay_from_boundary(&tokens, start_char, start_char == 0);
cursor.allow_metric_tolerance = false;
let result = (|| {
while !cursor.finished {
let row_frame_checkpoint = frame.try_append_checkpoint(storage)?;
let cursor_checkpoint = cursor.clone();
let mut candidate_height = frame_metrics_for_line(
fallback_font_size,
fallback_font_size,
line_spacing_type,
line_spacing_value,
dpi,
)
.line_height;
const MAX_ROW_HEIGHT_TRIALS: usize = 8;
let mut attempted_trials = storage.vec(MAX_ROW_HEIGHT_TRIALS)?;
loop {
frame.try_restore_append_checkpoint(&row_frame_checkpoint, storage)?;
cursor = cursor_checkpoint.clone();
let intervals =
storage.collect(frame.try_carve(candidate_height, storage)?.iter().cloned())?;
if !frame.carved_row_is_usable() {
return Ok(None);
}
let trial = (
frame.top,
candidate_height,
storage.collect(intervals.iter().cloned())?,
);
if attempted_trials.contains(&trial)
|| attempted_trials.len() == MAX_ROW_HEIGHT_TRIALS
{
return Ok(None);
}
attempted_trials.push(trial);
let mut segments = storage.vec(intervals.len())?;
let mut maximum_font_size = if start_char == 0 && frame.row_count() == first_row {
marker_font_size
} else {
0.0
};
let mut inline_metrics = (frame.row_count() == first_row)
.then_some(terminal_inline_metrics)
.flatten();
let mut inline_spacing_height = (frame.row_count() == first_row)
.then_some(terminal_inline_spacing_height)
.flatten();
let mut row_terminated = false;
let line_wrap_squeeze = styles
.para_styles
.get(para.para_shape_id as usize)
.is_some_and(|style| style.line_wrap_squeeze);
let interval_width = |index: usize, interval: &std::ops::Range<i32>| {
if line_wrap_squeeze {
return UNBROKEN_LINE_WIDTH_PX;
}
let width = crate::renderer::hwpunit_to_px(
interval.end.saturating_sub(interval.start),
dpi,
);
if index == 0 {
(width - marker_hang_px).max(1.0)
} else {
width
}
};
let widest_available_px = intervals
.iter()
.enumerate()
.map(|(index, interval)| interval_width(index, interval))
.fold(0.0, f64::max);
for (interval_index, interval) in intervals.into_iter().enumerate() {
let available_width_px = interval_width(interval_index, &interval);
let interval_indent_px = if interval_index == 0 { indent_px } else { 0.0 };
if cursor.fallback_char_idx.is_none() {
if let Some(BreakToken::Text {
base_width,
end_idx,
..
}) = tokens.get(cursor.token_index)
{
let word = FitWidthHwp::trimmed(
to_hwp(*base_width),
&letter_spacing_px,
*end_idx,
);
let fits = |width| {
text_token_fits_in_line_with_tolerance_hwp(
0, word, 0, width, None, 0,
)
};
let widest_available = to_hwp(widest_available_px);
if available_width_px < widest_available_px
&& !fits(to_hwp(available_width_px))
&& fits(widest_available)
{
let boundary =
char_index_to_utf16_offset(para, cursor.line_start_idx);
segments.push(RowSegment::new(
boundary..boundary,
interval,
source_tag | LineSeg::TAG_EMPTY_SEGMENT,
));
continue;
}
}
}
let tab_grid_origin_px = crate::renderer::hwpunit_to_px(interval.start, dpi)
+ if interval_index == 0 {
marker_hang_px
} else {
0.0
};
cursor.tab_grid_origin_px = Some(tab_grid_origin_px);
let terminal = terminal_tokens.as_ref().and_then(|terminal_tokens| {
let mut replay = FillCursor::replay_from_boundary(
terminal_tokens,
cursor.line_start_idx,
cursor.is_first_line,
);
replay.allow_metric_tolerance = false;
replay.tab_grid_origin_px = Some(tab_grid_origin_px);
let filled = fill_one_interval(
terminal_tokens,
&text_chars,
available_width_px,
interval_indent_px,
tab_fill,
korean_break_unit,
condense_min_space,
&letter_spacing_px,
&mut replay,
None,
)?;
(filled.termination == FillTermination::ParagraphEnd)
.then_some((filled, replay))
});
let selected_space_metric = if terminal.is_some() {
SpaceMetric::Stored
} else {
space_metric
};
let filled = if let Some((filled, replay)) = terminal {
cursor = replay;
filled
} else {
let Some(filled) = fill_one_interval(
&tokens,
&text_chars,
available_width_px,
interval_indent_px,
tab_fill,
korean_break_unit,
condense_min_space,
&letter_spacing_px,
&mut cursor,
kerning_break_session.as_mut(),
) else {
return Ok(None);
};
filled
};
let line = &filled.line;
if !zero_size_paragraph {
maximum_font_size = maximum_font_size.max(line.max_font_size);
}
if filled.termination == FillTermination::ParagraphEnd {
maximum_font_size = maximum_font_size.max(paragraph_end_font_size);
}
if filled.termination == FillTermination::ForcedBreak {
let break_font_size = line
.end_idx
.checked_sub(1)
.and_then(|idx| para.char_shape_id_at(idx))
.and_then(|id| styles.char_styles.get(id as usize))
.map_or(0.0, |style| style.font_size);
maximum_font_size = maximum_font_size.max(break_font_size);
}
for control in inline_controls.iter().filter(|control| {
inline_control_flow::owns_line(control, line, text_chars.len())
}) {
inline_spacing_height =
inline_spacing_height.max(control.spacing_height_hwp);
inline_metrics = match inline_metrics {
Some((height_hwp, baseline_distance_hwp))
if height_hwp > control.height_hwp =>
{
Some((height_hwp, baseline_distance_hwp))
}
Some((height_hwp, baseline_distance_hwp))
if height_hwp == control.height_hwp =>
{
Some((
height_hwp,
baseline_distance_hwp.max(control.baseline_distance_hwp),
))
}
_ => Some((control.height_hwp, control.baseline_distance_hwp)),
};
}
let text_start =
if start_char == 0 && frame.row_count() == first_row && segments.is_empty()
{
0
} else {
line_start_utf16_offset(para, line.start_idx, &inline_controls)
};
let text_end = line_start_utf16_offset(para, line.end_idx, &inline_controls)
.max(text_start);
let mut segment = RowSegment::new(text_start..text_end, interval, source_tag);
segment.space_metric = selected_space_metric;
segments.push(segment);
if filled.termination != FillTermination::IntervalFull {
row_terminated = true;
break;
}
}
if cursor.finished {
maximum_font_size =
maximum_font_size.max(paragraph_end_font_size_px(para, styles));
}
let mut metrics = frame_metrics_for_line(
maximum_font_size,
fallback_font_size,
line_spacing_type,
line_spacing_value,
dpi,
);
if let Some(height) = inline_spacing_height {
metrics.line_spacing = compute_line_spacing_hwp(
line_spacing_type,
line_spacing_value,
metrics.line_height.max(height),
dpi,
);
}
if let Some((height_hwp, baseline_distance_hwp)) = inline_metrics {
let inline_owns_row_height = height_hwp > metrics.line_height;
apply_inline_control_frame_height(&mut metrics, height_hwp);
if inline_owns_row_height {
if let Some(baseline_distance_hwp) = baseline_distance_hwp {
metrics.baseline_distance = baseline_distance_hwp;
}
}
}
if metrics.line_height != candidate_height {
candidate_height = metrics.line_height;
continue;
}
if row_terminated && segments.len() < frame.current_intervals.len() {
let text_start = segments
.last()
.map(|segment| segment.text_range.end)
.unwrap_or(0);
for interval in frame.current_intervals[segments.len()..].iter().cloned() {
segments.push(RowSegment::new(
text_start..text_start,
interval,
source_tag | LineSeg::TAG_EMPTY_SEGMENT,
));
}
}
let indented = if start_char == 0 && frame.row_count() == first_row {
indentation_pattern.0
} else {
indentation_pattern.1
};
let head = start_char == 0
&& frame.row_count() == first_row
&& paragraph_has_head(para_style);
for (index, segment) in segments.iter_mut().enumerate() {
if indented && index == 0 {
segment.source_tag |= LineSeg::TAG_INDENTATION;
} else {
segment.source_tag &= !LineSeg::TAG_INDENTATION;
}
if head && index == 0 {
segment.source_tag |= LineSeg::TAG_PARAGRAPH_HEAD;
}
}
if frame
.try_commit_carved_row(metrics, segments, storage)?
.is_none()
{
return Ok(None);
}
break;
}
}
if para.line_segs.is_empty() && supports_tac_table_band_frame_controls(para) {
frame.try_absorb_whitespace_only_rows(¶.text, first_row, storage)?;
}
Ok(Some(frame.try_project_line_segs_since(first_row, storage)?))
})();
let kerning_failed = kerning_break_session
.as_ref()
.and_then(|session| session.failed_reason())
.is_some();
if !matches!(result, Ok(Some(_))) {
frame.restore_owned_append_checkpoint(frame_checkpoint);
}
drop(kerning_break_session);
drop(kerning_transaction);
if kerning_failed && result.is_ok() {
return try_layout_paragraph_in_frame_impl(
para,
frame,
styles,
dpi,
false,
FrameStart::Scalar(start_char),
purpose,
storage,
);
}
result
}
pub(crate) fn stored_row_metrics(
para: &Paragraph,
styles: &ResolvedStyleSet,
dpi: f64,
row: &[LineSeg],
) -> Option<FrameRowMetrics> {
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let line_spacing_type = para_style
.map(|style| style.line_spacing_type)
.unwrap_or(LineSpacingType::Percent);
let line_spacing_value = para_style.map(|style| style.line_spacing).unwrap_or(160.0);
let fallback_font_size = para
.char_shapes
.first()
.and_then(|shape| styles.char_styles.get(shape.char_shape_id as usize))
.map(|style| style.font_size)
.unwrap_or(12.0);
let span_start = row.first()?.text_start;
let row_end = row.last()?.text_start;
let span_end = para
.line_segs
.iter()
.map(|segment| segment.text_start)
.filter(|start| *start > row_end)
.min()
.unwrap_or(u32::MAX);
let active = para
.char_shapes
.iter()
.filter(|shape| shape.start_pos <= span_start)
.map(|shape| shape.start_pos)
.max();
let max_font_size = para
.char_shapes
.iter()
.filter(|shape| {
(shape.start_pos >= span_start && shape.start_pos < span_end)
|| Some(shape.start_pos) == active
})
.filter_map(|shape| styles.char_styles.get(shape.char_shape_id as usize))
.map(|style| style.font_size)
.fold(0.0f64, f64::max);
Some(frame_metrics_for_line(
list_marker_metrics::include_marker(para, styles, span_start == 0, max_font_size),
fallback_font_size,
line_spacing_type,
line_spacing_value,
dpi,
))
}
fn stored_inline_row_metrics(
para: &Paragraph,
styles: &ResolvedStyleSet,
dpi: f64,
row: &[LineSeg],
controls: &[FlowInlineControl],
) -> Option<FrameRowMetrics> {
let mut metrics = stored_row_metrics(para, styles, dpi, row)?;
let start = row.first()?.text_start;
let last = row.last()?.text_start;
let end = para
.line_segs
.iter()
.map(|segment| segment.text_start)
.filter(|offset| *offset > last)
.min()
.unwrap_or(u32::MAX);
let mut inline_height = 0;
let mut inline_baseline = None;
let mut spacing_height = 0;
for control in controls
.iter()
.filter(|control| control.utf16_position >= start && control.utf16_position < end)
{
spacing_height = spacing_height.max(control.spacing_height_hwp.unwrap_or(0));
if control.height_hwp > inline_height {
inline_height = control.height_hwp;
inline_baseline = control.baseline_distance_hwp;
} else if control.height_hwp == inline_height {
inline_baseline = inline_baseline.max(control.baseline_distance_hwp);
}
}
if spacing_height > 0 {
let style = styles.para_styles.get(para.para_shape_id as usize);
metrics.line_spacing = compute_line_spacing_hwp(
style.map_or(LineSpacingType::Percent, |style| style.line_spacing_type),
style.map_or(160.0, |style| style.line_spacing),
metrics.line_height.max(spacing_height),
dpi,
);
}
if inline_height > metrics.line_height {
apply_inline_control_frame_height(&mut metrics, inline_height);
if let Some(baseline) = inline_baseline {
metrics.baseline_distance = baseline;
}
}
Some(metrics)
}
pub(crate) fn resolve_stored_line_segs_in_frame(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
legacy_hwp3_stored_geometry: bool,
miss_policy: StoredRowMissPolicy,
stale: bool,
float_carve_evidence: &[crate::renderer::float_placement::FloatCarveEvidence],
known_square_band: bool,
) -> Option<StoredRowResolution> {
match resolve_stored_line_segs_in_frame_with_storage(
para,
frame,
styles,
dpi,
legacy_hwp3_stored_geometry,
miss_policy,
stale,
float_carve_evidence,
known_square_band,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn resolve_stored_line_segs_in_frame_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
legacy_hwp3_stored_geometry: bool,
miss_policy: StoredRowMissPolicy,
stale: bool,
float_carve_evidence: &[crate::renderer::float_placement::FloatCarveEvidence],
known_square_band: bool,
storage: &S,
) -> Result<Option<StoredRowResolution>, S::Error> {
let rollback = if S::UNBOUNDED {
None
} else {
Some(frame.try_append_checkpoint(storage)?)
};
let resolved = (|| -> Result<Option<StoredRowResolution>, S::Error> {
Ok({
let tac_table_host_fill = para.line_segs.is_empty()
&& (supports_tac_table_band_frame_controls(para)
|| supports_overlay_table_frame_controls(para)
|| supports_overlay_shape_frame_controls(para));
if !supports_picture_band_frame_controls(para)
&& !tac_table_host_fill
&& !no_ls_inline_picture_host_fill(para)
&& !(para.line_segs.is_empty() && supports_inline_form_frame_controls(para))
{
if !supports_cached_body_frame_controls(para)
|| (!stale && !para.line_segs.is_empty())
{
return Ok(None);
}
}
if para.line_segs.is_empty() {
return Ok(layout_paragraph_in_frame_with_storage(
para, frame, styles, dpi, storage,
)?
.map(|_| StoredRowResolution::Reflowed));
}
if legacy_hwp3_stored_geometry && !stale {
return Ok(None);
}
if !stale
&& !para.stored_text_partition_is_dirty()
&& super::stored_row_fragments::crosses_physical_frame(para)
{
return Ok(None);
}
if !frame.models_exclusions()
&& stored_rows_require_external_geometry(
para,
frame,
float_carve_evidence,
known_square_band,
)
{
return Ok(None);
}
if let Some(start_row) = remeasured_equation_start_row(para) {
let checkpoint = frame.try_append_checkpoint(storage)?;
let prefix_controls = flow_inline_controls_with_storage(para, styles, storage)?;
if !para.stored_text_partition_is_dirty()
&& !stored_rows_require_external_geometry(
para,
frame,
float_carve_evidence,
known_square_band,
)
&& (start_row == 0
|| frame.try_admit_stored_rows_with_storage(
¶.line_segs[..start_row],
|row| {
stored_inline_row_metrics(para, styles, dpi, row, &prefix_controls)
},
storage,
)?)
{
if try_layout_paragraph_in_frame_impl(
para,
frame,
styles,
dpi,
true,
FrameStart::SourceUtf16(para.line_seg_text_start(start_row)),
FramePurpose::Body,
storage,
)?
.is_some()
{
return Ok(Some(StoredRowResolution::Reflowed));
}
}
frame.restore_owned_append_checkpoint(checkpoint);
return Ok(None);
}
let entry_checkpoint = frame.try_append_checkpoint(storage)?;
let cache_geometry_matches = stored_rows_reproduce_frame_expectation_with_storage(
para, frame, styles, dpi, storage,
)?;
if cache_geometry_matches && !stale {
return Ok(Some(StoredRowResolution::Stored));
}
frame.restore_owned_append_checkpoint(entry_checkpoint);
if !cache_geometry_matches
&& !stale
&& miss_policy == StoredRowMissPolicy::UnmodelledUnlessStale
{
return Ok(None);
}
if !cache_geometry_matches {
report_stored_row_key_mismatch_with_storage(para, frame, styles, dpi, storage)?;
}
let mut reflow_input = storage.clone_paragraph(para)?;
reflow_input.line_segs.clear();
layout_paragraph_in_frame_with_storage(&reflow_input, frame, styles, dpi, storage)?
.map(|_| StoredRowResolution::Reflowed)
})
})();
if resolved.is_err() {
if let Some(checkpoint) = rollback {
frame.restore_owned_append_checkpoint(checkpoint);
}
}
resolved
}
const FLOAT_CARVE_MATCH_TOLERANCE_HU: i32 = 1200;
const UNIFORM_INSET_MIN_DELTA_HU: i32 = 4;
pub(crate) fn stored_rows_reproduce_frame_expectation(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
) -> bool {
match stored_rows_reproduce_frame_expectation_with_storage(
para,
frame,
styles,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn stored_rows_reproduce_frame_expectation_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
frame: &mut LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<bool, S::Error> {
Ok({
frame.try_admit_stored_rows_with_storage(
¶.line_segs,
|row| stored_row_metrics(para, styles, dpi, row),
storage,
)?
})
}
fn report_stored_row_key_mismatch(
para: &Paragraph,
frame: &LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
) {
match report_stored_row_key_mismatch_with_storage(
para,
frame,
styles,
dpi,
&crate::storage::Unbounded,
) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn report_stored_row_key_mismatch_with_storage<S: crate::storage::Storage>(
para: &Paragraph,
frame: &LayoutFrame,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<(), S::Error> {
let _: () = {
if std::env::var_os("RHWP_DIAG_STORED_ROW_KEY").is_none() {
return Ok(());
}
let mut probe = crate::storage::try_clone(frame, storage)?;
if !stored_rows_reproduce_frame_expectation_with_storage(
para, &mut probe, styles, dpi, storage,
)? {
eprintln!(
"DIAG_STORED_ROW_KEY mismatch rows={} stored=[{}]",
para.line_segs.len(),
{
let mut entries = storage.vec(para.line_segs.len())?;
for segment in ¶.line_segs {
entries.push(storage.display(&format_args!(
"{}+{}",
segment.column_start, segment.segment_width
))?);
}
storage.join(&entries, " ")?
},
);
}
};
Ok(())
}
fn picture_band_paragraph_reference(
column_horizontal: &Range<i32>,
host_margin_left: i32,
) -> Option<Range<i32>> {
let start = column_horizontal.start.saturating_add(host_margin_left);
(start < column_horizontal.end).then_some(start..column_horizontal.end)
}
pub(crate) fn layout_picture_band(
paragraphs: &[Paragraph],
host_index: usize,
column_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
paper_origin_px: (f64, f64),
) -> Option<PictureBandLayout> {
layout_picture_band_impl(
paragraphs,
host_index,
column_width_px,
styles,
dpi,
paper_origin_px,
false,
)
}
pub(crate) fn layout_container_picture_band(
paragraphs: &[Paragraph],
host_index: usize,
column_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
admit_stored: bool,
) -> Option<PictureBandLayout> {
layout_picture_band_impl(
paragraphs,
host_index,
column_width_px,
styles,
dpi,
(0.0, 0.0),
admit_stored,
)
}
fn layout_picture_band_impl(
paragraphs: &[Paragraph],
host_index: usize,
column_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
paper_origin_px: (f64, f64),
admit_stored: bool,
) -> Option<PictureBandLayout> {
let host = paragraphs.get(host_index)?;
let column_horizontal = 0..px_to_hwpunit(column_width_px, dpi);
let margins_for = |paragraph: &Paragraph| {
let style = styles.para_styles.get(paragraph.para_shape_id as usize);
(
style.map(|value| value.margin_left).unwrap_or(0.0),
style.map(|value| value.margin_right).unwrap_or(0.0),
)
};
let box_for = |paragraph: &Paragraph| {
let paragraph_box = ParagraphBox::body_for_style(
column_width_px,
styles.para_styles.get(paragraph.para_shape_id as usize),
dpi,
);
paragraph_box.is_usable().then_some(paragraph_box)
};
let host_box = box_for(host)?;
let host_horizontal = host_box.effective();
let host_margin_left = px_to_hwpunit(margins_for(host).0, dpi);
let host_paragraph_horizontal =
picture_band_paragraph_reference(&column_horizontal, host_margin_left)?;
let band_objects: Vec<(usize, &Control)> = host
.controls
.iter()
.enumerate()
.filter(|(_, control)| control_owns_body_band(control))
.collect();
if band_objects.is_empty()
|| band_objects
.iter()
.filter(|(_, control)| matches!(control, Control::Picture(_)))
.count()
> 1
{
return None;
}
let mut anchor_input = host.clone();
anchor_input.line_segs.clear();
let mut anchor_frame = host_box.frame(0);
let anchor_rows = layout_paragraph_in_frame(&anchor_input, &mut anchor_frame, styles, dpi)?;
let raw_positions = host.control_utf16_positions();
let paper = crate::renderer::float_placement::PaperOrigin {
body_left: px_to_hwpunit(paper_origin_px.0, dpi),
body_top: px_to_hwpunit(paper_origin_px.1, dpi),
band_abs_top: host
.line_segs
.iter()
.find(|seg| seg.tag & 0x8000_0000 == 0)
.map(|seg| seg.vertical_pos)
.unwrap_or(0),
};
let mut exclusions = Vec::with_capacity(band_objects.len());
for (control_index, control) in band_objects {
let raw_start = raw_positions.get(control_index).copied()?;
let anchor_top = anchor_rows
.iter()
.rfind(|row| row.text_start <= raw_start)
.map(|row| row.vertical_pos)?;
let exclusion = match control {
Control::Picture(picture) => {
crate::renderer::float_placement::resolve_picture_exclusion(
picture,
column_horizontal.clone(),
host_paragraph_horizontal.clone(),
anchor_top,
paper,
)
}
Control::Shape(shape) => crate::renderer::float_placement::resolve_shape_exclusion(
shape.common(),
column_horizontal.clone(),
host_paragraph_horizontal.clone(),
anchor_top,
paper,
),
_ => None,
}?;
exclusions.push(exclusion);
}
let exclusion_end = exclusions
.iter()
.map(|exclusion| exclusion.vertical.end)
.max()?;
let mut frame = host_box.frame_with(0, exclusions);
let mut line_segs = Vec::new();
let mut space_metrics = Vec::new();
let mut preserved_stored = Vec::new();
for (paragraph_index, paragraph) in paragraphs.iter().enumerate().skip(host_index) {
if frame.top >= exclusion_end {
break;
}
let paragraph_style = styles.para_styles.get(paragraph.para_shape_id as usize);
let successor = paragraph_index != host_index;
if (successor && paragraph.column_type != ColumnBreakType::None)
|| paragraph_style.is_some_and(|style| {
style.spacing_before.abs() > f64::EPSILON
|| style.spacing_after.abs() > f64::EPSILON
|| (successor && style.page_break_before)
})
|| box_for(paragraph)?.effective() != host_horizontal
|| (successor && paragraph.controls.iter().any(control_owns_body_band))
{
return None;
}
let mut input = paragraph.clone();
let first_row = frame.row_count();
let preserved = if admit_stored && !crate::renderer::para_has_no_stored_line_segs(paragraph)
{
resolve_stored_line_segs_in_frame(
paragraph,
&mut frame,
styles,
dpi,
false,
StoredRowMissPolicy::Reflow,
paragraph.stored_text_partition_is_dirty(),
&[],
true,
)? == StoredRowResolution::Stored
} else {
input.line_segs.clear();
layout_paragraph_in_frame(&input, &mut frame, styles, dpi)?;
false
};
let paragraph_lines = if preserved {
paragraph.line_segs.clone()
} else {
frame.project_line_segs_since(first_row)
};
space_metrics.push(frame.project_space_metrics_since(first_row));
line_segs.push(paragraph_lines);
preserved_stored.push(preserved);
}
let band_closed = frame.top >= exclusion_end
|| (host_index + line_segs.len() == paragraphs.len()
&& paragraphs[host_index..]
.iter()
.zip(&line_segs)
.any(|(paragraph, rows)| {
paragraph.text.chars().any(|ch| !ch.is_whitespace())
&& rows.iter().any(|row| {
row_is_carved_from_box(
row.column_start,
row.segment_width,
&host_horizontal,
)
})
}));
(!line_segs.is_empty() && band_closed).then_some(PictureBandLayout {
paragraph_range: host_index..host_index + line_segs.len(),
line_segs,
space_metrics,
preserved_stored,
})
}
pub(crate) fn reflow_line_segs(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
) {
let _ = reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, false, true);
super::equation_line_metrics::publish_regenerated_rows(para, styles);
}
pub(crate) fn reflow_line_segs_after_cell_split(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
) {
let _ = reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, true, true);
super::equation_line_metrics::publish_regenerated_rows(para, styles);
}
pub(crate) fn reflow_line_segs_after_cell_text_edit(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
edit_char_offset: usize,
) -> bool {
let preserved = reflow_line_segs_impl(
para,
paragraph_box,
styles,
dpi,
Some(edit_char_offset),
false,
true,
);
super::equation_line_metrics::publish_regenerated_rows(para, styles);
preserved
}
pub(crate) fn reflow_line_segs_in_stored_section(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
) {
let _ = reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, false, true);
super::equation_line_metrics::publish_regenerated_rows(para, styles);
}
fn reflow_line_segs_impl(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
preserve_prefix_for_edit: Option<usize>,
split_stale_cell_reflow: bool,
object_line_font_basis: bool,
) -> bool {
match try_reflow_line_segs_impl(
para,
paragraph_box,
styles,
dpi,
preserve_prefix_for_edit,
split_stale_cell_reflow,
object_line_font_basis,
&Unbounded,
) {
Ok(result) => result,
Err(never) => match never {},
}
}
pub(crate) fn try_reflow_line_segs<S: Storage>(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
storage: &S,
) -> Result<(), S::Error> {
try_reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, false, true, storage)?;
super::equation_line_metrics::publish_regenerated_rows(para, styles);
Ok(())
}
fn try_reflow_line_segs_impl<S: Storage>(
para: &mut Paragraph,
paragraph_box: ParagraphBox,
styles: &ResolvedStyleSet,
dpi: f64,
preserve_prefix_for_edit: Option<usize>,
split_stale_cell_reflow: bool,
object_line_font_basis: bool,
storage: &S,
) -> Result<bool, S::Error> {
if !paragraph_box.is_usable() {
return Ok(false);
}
if para.stored_text_partition_is_dirty() {
let tab_count = para.text.chars().filter(|&ch| ch == '\t').count();
for extension in para.tab_extended.iter_mut().take(tab_count) {
if extension[2] >> 8 == 2 {
extension[0] = 0;
extension[1] = 0;
}
}
}
para.layout_only_fill_lines = 0;
let orig = para.line_segs.first().cloned();
let published_horizontal = paragraph_box.effective();
let seg_width_hwp = paragraph_box.width_hwp();
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let indent_px = if reflow_indentation_pattern(para_style, ¶.line_segs, seg_width_hwp)
== (false, false)
{
0.0
} else {
para_style.map_or(0.0, |style| style.indent)
};
let (marker_hang_px, indent_px) = list_marker_breaker_box(para, styles, indent_px);
let available_width_px = (paragraph_box.width_px(dpi) - marker_hang_px).max(1.0);
let line_wrap_squeeze = para_style.is_some_and(|style| style.line_wrap_squeeze);
let available_width_px = if line_wrap_squeeze {
UNBROKEN_LINE_WIDTH_PX
} else {
available_width_px
};
if !split_stale_cell_reflow
&& (supports_inline_picture_frame_controls(para)
|| supports_inline_form_frame_controls(para))
{
let mut input = storage.clone_record(para)?;
input.line_segs.clear();
let mut frame = paragraph_box.frame(orig.as_ref().map_or(0, |line| line.vertical_pos));
if let Some(lines) = try_layout_paragraph_in_frame_impl(
&input,
&mut frame,
styles,
dpi,
true,
FrameStart::Scalar(0),
FramePurpose::Body,
storage,
)? {
para.replace_line_segs_with_space_metrics(
lines,
frame.try_project_space_metrics_since(0, storage)?,
);
return Ok(false);
}
}
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let ls_type = para_style
.map(|s| s.line_spacing_type)
.unwrap_or(LineSpacingType::Percent);
let ls_value = para_style.map(|s| s.line_spacing).unwrap_or(160.0);
let zero_size_paragraph = explicit_zero_size_paragraph(para, styles);
let make_line_seg = |utf16_start: u32, max_font_size: f64| -> LineSeg {
let max_font_size =
list_marker_metrics::include_marker(para, styles, utf16_start == 0, max_font_size);
let fs = if max_font_size > 0.0 {
max_font_size
} else if zero_size_paragraph {
0.0
} else {
12.0
};
let line_height_hwp = font_size_to_line_height(fs, dpi);
let text_height_hwp = line_height_hwp;
let baseline_distance_hwp = baseline_distance_hwp(line_height_hwp);
let line_spacing_hwp = compute_line_spacing_hwp(ls_type, ls_value, line_height_hwp, dpi);
let orig_tag = orig
.as_ref()
.map(|ls| ls.tag)
.unwrap_or(LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY);
LineSeg {
text_start: utf16_start,
line_height: line_height_hwp,
text_height: text_height_hwp,
baseline_distance: baseline_distance_hwp,
line_spacing: line_spacing_hwp,
column_start: published_horizontal.start,
segment_width: seg_width_hwp,
tag: if orig_tag != 0 {
orig_tag
} else {
LineSeg::TAG_SINGLE_SEGMENT_LINE
},
..Default::default()
}
};
if para.text.is_empty() {
let inline_sizes = storage.collect(
para.controls
.iter()
.enumerate()
.scan(0u32, |utf16_pos, (index, ctrl)| {
let start = *utf16_pos
+ para.trailing_auxiliary_slots_before(index) * CTRL_CHAR_CODE_UNITS;
if ctrl.occupies_ctrl_char_slot() {
*utf16_pos += CTRL_CHAR_CODE_UNITS;
}
Some((start, ctrl))
})
.filter_map(|(start, ctrl)| {
inline_control_occupied_size_hwp(ctrl, styles, dpi)
.map(|occupied| (start, Some(occupied)))
.or_else(|| {
(matches!(ctrl, Control::Field(_))
|| inline_frame_input::is_nonflow_anchor(ctrl))
.then_some((start, None))
})
}),
)?;
if inline_sizes.iter().any(|(_, occupied)| occupied.is_some()) {
let max_line_width = |line_index: usize| {
let indent = if line_index == 0 {
indent_px.max(0.0)
} else {
(-indent_px).max(0.0)
};
px_to_hwpunit((available_width_px - indent).max(1.0), dpi)
};
let mut line_specs: Vec<(u32, i32, i32)> = Vec::new();
let mut line_start = 0u32;
let mut line_width = 0i32;
let mut line_height = 0i32;
let mut line_has_anchor = false;
for (utf16_start, occupied) in inline_sizes.iter().copied() {
let (ctrl_width, ctrl_height) = occupied.unwrap_or((0, 0));
if (line_width > 0 || line_has_anchor)
&& line_width + ctrl_width > max_line_width(line_specs.len())
{
storage.push(&mut line_specs, (line_start, line_width, line_height))?;
line_start = utf16_start;
line_width = 0;
line_height = 0;
line_has_anchor = false;
}
line_has_anchor |= occupied.is_none();
line_width += ctrl_width;
line_height = line_height.max(ctrl_height);
}
storage.push(&mut line_specs, (line_start, line_width, line_height))?;
let orig_line_segs = storage.collect(para.line_segs.iter().cloned())?;
let mut new_line_segs = storage.vec(line_specs.len())?;
let negative_percent_spacing =
matches!(ls_type, LineSpacingType::Percent) && ls_value < 100.0;
let paragraph_font_px = if object_line_font_basis || negative_percent_spacing {
paragraph_font_size_px(para, styles).unwrap_or(12.0)
} else {
0.0
};
for (line_idx, (start_pos, _line_width, height_hwp)) in
line_specs.into_iter().enumerate()
{
let mut seg = make_line_seg(start_pos, paragraph_font_px);
if let Some(template) = orig_line_segs
.get(line_idx)
.or_else(|| orig_line_segs.first())
{
seg.line_spacing = template.line_spacing;
seg.segment_width = if template.segment_width > 0 {
template.segment_width
} else {
seg_width_hwp
};
seg.tag = if template.tag != 0 {
template.tag
} else {
seg.tag
};
}
apply_inline_control_line_height(&mut seg, height_hwp);
storage.push(&mut new_line_segs, seg)?;
}
if split_stale_cell_reflow {
apply_reflowed_equation_row_metrics(
para,
&mut new_line_segs,
styles,
ls_type,
ls_value,
dpi,
);
}
let mut vpos = orig.as_ref().map(|ls| ls.vertical_pos).unwrap_or(0);
for seg in &mut new_line_segs {
seg.vertical_pos = vpos;
vpos += seg.line_height.saturating_add(seg.line_spacing);
}
mark_indented_lines(
&mut new_line_segs,
0,
para_style,
&orig_line_segs,
seg_width_hwp,
);
para.replace_line_segs(new_line_segs);
} else {
let font_size = paragraph_font_size_px(para, styles).unwrap_or(12.0);
let mut seg = make_line_seg(0, font_size);
if let Some(template) = orig.as_ref() {
seg.vertical_pos = template.vertical_pos;
if template.segment_width == 0
&& matches!(para.controls.as_slice(), [Control::Table(table)]
if !table.common.treat_as_char)
{
seg.segment_width = 0;
}
}
if let Some(height_hwp) = inline_control_line_height_hwp(para) {
apply_inline_control_line_height(&mut seg, height_hwp);
}
if let Some((height_hwp, baseline)) =
inline_control_flow::empty_text_ruby_row(para, styles)
{
if height_hwp > seg.line_height {
apply_inline_control_line_height(&mut seg, height_hwp);
seg.baseline_distance = baseline;
seg.line_spacing = compute_line_spacing_hwp(ls_type, ls_value, height_hwp, dpi);
}
}
mark_indented_lines(
std::slice::from_mut(&mut seg),
0,
para_style,
¶.line_segs,
seg_width_hwp,
);
para.replace_line_segs(storage.collect([seg])?);
}
return Ok(false);
}
let frame_eligible = !split_stale_cell_reflow
&& preserve_prefix_for_edit.is_none()
&& !para.text.is_empty()
&& para.controls.is_empty();
if frame_eligible {
let mut frame =
paragraph_box.frame(orig.as_ref().map(|line| line.vertical_pos).unwrap_or(0));
if let Some(projected) = try_layout_paragraph_in_frame_impl(
para,
&mut frame,
styles,
dpi,
true,
FrameStart::Scalar(0),
FramePurpose::Body,
storage,
)? {
para.replace_line_segs_with_space_metrics(
projected,
frame.try_project_space_metrics_since(0, storage)?,
);
return Ok(false);
}
}
let mut text_chars = storage.collect(para.text.chars())?;
for (position, _) in ¶.layout_field_values {
if let Some(character) = text_chars.get_mut(*position) {
*character = '\u{0015}';
}
}
let text_len = text_chars.len();
let inline_controls = flow_inline_controls_with_storage(para, styles, storage)?;
let para_style = styles.para_styles.get(para.para_shape_id as usize);
let english_break_unit = para_style.map(|s| s.english_break_unit).unwrap_or(0);
let korean_break_unit = para_style.map(|s| s.korean_break_unit).unwrap_or(0);
let condense_min_space = para_style.map(|s| s.condense_min_space).unwrap_or(0);
let reflow_space_metric = if split_stale_cell_reflow {
SpaceMetric::HancomRegenerated
} else {
SpaceMetric::Stored
};
let mut tokens = try_tokenize_paragraph_with_regenerated_space_metric(
&text_chars,
¶.char_offsets,
¶.char_shapes,
styles,
english_break_unit,
korean_break_unit,
reflow_space_metric,
&inline_controls,
para.control_mask & (1 << 0x18) != 0,
¶.literal_figure_spaces,
storage,
)?;
apply_resolved_field_tokens_with_storage(para, styles, &inline_controls, &mut tokens, storage)?;
apply_auto_left_tab_targets(&mut tokens, para_style);
let prepared_kerning = prepare_paragraph_kerning(
para,
&text_chars,
styles,
reflow_space_metric,
&inline_controls,
)
.and_then(|prepared| {
apply_paragraph_kerning_to_tokens(&mut tokens, &prepared.measurement).map(|_| prepared)
});
let original_line_segs = storage.collect(para.line_segs.iter().cloned())?;
let token_start_idx = |token: &BreakToken| match token {
BreakToken::Text { start_idx, .. } => *start_idx,
BreakToken::DiscretionaryHyphen { idx, .. }
| BreakToken::Space { idx, .. }
| BreakToken::Tab { idx, .. }
| BreakToken::LineBreak { idx } => *idx,
};
let mut preserved_prefix = Vec::new();
let mut reflow_start_idx = 0usize;
let mut reflow_is_first_line = true;
let mut token_start = 0usize;
let has_valid_orig = original_line_segs
.iter()
.all(|seg| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
let authoritative_line_seg_prefix = has_valid_orig
&& original_line_segs
.first()
.is_some_and(|seg| seg.text_start == 0)
&& original_line_segs
.windows(2)
.all(|pair| pair[0].text_start < pair[1].text_start);
if para.controls.is_empty() && authoritative_line_seg_prefix {
if let Some(edit_char_offset) = preserve_prefix_for_edit {
let edit_is_document_end = edit_char_offset == text_len;
let edit_utf16 = para
.char_offsets
.get(edit_char_offset)
.copied()
.or_else(|| edit_is_document_end.then(|| para.text.encode_utf16().count() as u32));
let affected_line = edit_utf16.and_then(|offset| {
let line = original_line_segs
.iter()
.rposition(|seg| seg.text_start <= offset)?;
if edit_is_document_end && original_line_segs[line].text_start < offset {
line.checked_sub(1)
} else {
Some(line)
}
});
if let Some(affected_line) = affected_line.filter(|line| *line > 0) {
let reflow_utf16 = original_line_segs[affected_line].text_start;
let reflow_char_idx = para
.char_offsets
.iter()
.position(|offset| *offset == reflow_utf16);
let suffix_token_start = reflow_char_idx.and_then(|char_idx| {
tokens
.iter()
.position(|token| token_start_idx(token) == char_idx)
.map(|token_idx| (char_idx, token_idx))
});
if let Some((char_idx, token_idx)) = suffix_token_start {
preserved_prefix =
storage.collect(original_line_segs[..affected_line].iter().cloned())?;
reflow_start_idx = char_idx;
reflow_is_first_line = false;
token_start = token_idx;
}
}
}
}
let mut kerning_transaction = prepared_kerning
.as_ref()
.map(|prepared| prepared.context.layout_session());
let mut kerning_break_session = prepared_kerning.as_ref().and_then(|prepared| {
crate::renderer::kerning::KerningParagraphBreakSession::new(
¶.text,
&prepared.scalar_styles,
&prepared.hard_boundaries,
&prepared.measurement,
kerning_transaction.as_mut()?,
)
.ok()
});
let mut line_breaks = try_fill_lines(
&tokens[token_start..],
&text_chars,
available_width_px,
indent_px,
TabFill::for_paragraph(para_style, indent_px, available_width_px)
.with_stop_overflow_wraps(styles),
korean_break_unit,
condense_min_space,
&try_resolved_paragraph_letter_spacing(
para,
&text_chars,
styles,
reflow_space_metric,
storage,
)?,
reflow_start_idx,
reflow_is_first_line,
!split_stale_cell_reflow,
kerning_break_session.as_mut(),
storage,
)?;
let kerning_failed = kerning_break_session
.as_ref()
.and_then(|session| session.failed_reason())
.is_some();
drop(kerning_break_session);
drop(kerning_transaction);
if kerning_failed {
line_breaks = try_fill_lines(
&tokens[token_start..],
&text_chars,
available_width_px,
indent_px,
TabFill::for_paragraph(para_style, indent_px, available_width_px)
.with_stop_overflow_wraps(styles),
korean_break_unit,
condense_min_space,
&try_resolved_paragraph_letter_spacing(
para,
&text_chars,
styles,
reflow_space_metric,
storage,
)?,
reflow_start_idx,
reflow_is_first_line,
!split_stale_cell_reflow,
None,
storage,
)?;
}
let edited_tac_table = supports_tac_table_band_frame_controls(para);
let table_indent_px = if edited_tac_table
&& reflow_indentation_pattern(para_style, &original_line_segs, seg_width_hwp)
== (false, false)
{
0.0
} else {
indent_px
};
let terminal_inline_control = para
.controls
.iter()
.zip(para.try_control_text_positions(storage)?)
.any(|(control, position)| position == text_len && control.is_treat_as_char_object());
let occupied_controls: Vec<_> = if split_stale_cell_reflow
|| edited_tac_table
|| terminal_inline_control
|| inline_controls.is_empty()
{
para.controls
.iter()
.zip(para.control_text_positions())
.zip(para.control_utf16_positions())
.filter_map(|((control, position), utf16_start)| {
let (width, height) = inline_control_occupied_size_hwp(control, styles, dpi)?;
Some((position, utf16_start, width, height))
})
.collect()
} else {
Vec::new()
};
let forced_inline_line =
(split_stale_cell_reflow || edited_tac_table || terminal_inline_control)
.then(|| {
inline_control_requires_own_line(
para,
&occupied_controls,
&text_chars,
&line_breaks,
available_width_px,
table_indent_px,
reflow_is_first_line,
styles,
reflow_space_metric,
)
})
.flatten();
let floating_anchors = floating_anchor_char_font_sizes_with_storage(para, styles, storage)?;
let preserved_prefix_len = preserved_prefix.len();
let mut new_line_segs: Vec<LineSeg> = preserved_prefix;
for (line_idx, lb) in line_breaks.iter().enumerate() {
storage.reserve(&mut new_line_segs, 3)?;
let utf16_start = if new_line_segs.is_empty() {
0 } else {
match forced_inline_line {
Some((position, control_start, ..)) if position == lb.start_idx => control_start,
_ => line_start_utf16_offset(para, lb.start_idx, &inline_controls),
}
};
let fs = if lb.max_font_size > 0.0 && !zero_size_paragraph {
lb.max_font_size
} else {
paragraph_font_size_px(para, styles).unwrap_or(12.0)
};
let fs = fs.max(floating_anchor_font_size_px(
&floating_anchors,
lb.start_idx..lb.end_idx,
lb.end_idx == text_len,
text_len,
));
let fs = if line_idx + 1 == line_breaks.len() {
fs.max(paragraph_end_font_size_px(para, styles))
} else {
fs
};
let mut text_seg = make_line_seg(utf16_start, fs);
let field_led_row =
line_idx == 0 && forced_inline_line.is_some_and(|(position, ..)| position == 0);
let control_after_text = field_led_row
|| forced_inline_line.is_some_and(|(position, ..)| {
position > lb.start_idx
&& (position < lb.end_idx
|| (position == lb.end_idx && line_idx + 1 == line_breaks.len()))
});
if !field_led_row
&& forced_inline_line.is_some_and(|(position, ..)| position == lb.start_idx)
{
let (_, _, height_hwp, _) = forced_inline_line.expect("checked inline control");
apply_inline_control_line_height(&mut text_seg, height_hwp);
}
if let Some(control) = inline_controls
.iter()
.filter(|control| {
inline_control_flow::owns_line(control, lb, text_len)
&& !(control_after_text
&& forced_inline_line
.is_some_and(|(position, ..)| position == control.char_position))
})
.filter(|control| {
!forced_inline_line.is_some_and(|(position, start, ..)| {
position > lb.start_idx && start == control.utf16_position
})
})
.max_by_key(|control| (control.height_hwp, control.baseline_distance_hwp))
{
let inline_owns_row_height = control.height_hwp > text_seg.line_height;
apply_inline_control_line_height(&mut text_seg, control.height_hwp);
if inline_owns_row_height {
if let Some(baseline) = control.baseline_distance_hwp {
text_seg.baseline_distance = baseline;
}
if let Some(height) = control.spacing_height_hwp {
text_seg.line_spacing = compute_line_spacing_hwp(
ls_type,
ls_value,
text_seg.line_height.max(height),
dpi,
);
}
}
}
new_line_segs.push(text_seg);
if control_after_text {
let (_, control_start, height_hwp, _) =
forced_inline_line.expect("checked inline control");
let mut control_seg = make_line_seg(control_start, fs);
apply_inline_control_line_height(&mut control_seg, height_hwp);
new_line_segs.push(control_seg);
}
if let Some((position, _, _, true)) = forced_inline_line
.filter(|(position, ..)| control_after_text || *position == lb.start_idx)
{
new_line_segs.push(make_line_seg(
char_index_to_utf16_offset(para, position),
fs,
));
}
}
if new_line_segs.is_empty() {
storage.reserve(&mut new_line_segs, 1)?;
new_line_segs.push(make_line_seg(
0,
paragraph_font_size_px(para, styles).unwrap_or(12.0),
));
}
if forced_inline_line.is_none() && inline_controls.is_empty() {
for &(position, _, _, height_hwp) in &occupied_controls {
let line_index = line_breaks
.iter()
.rposition(|line| line.start_idx <= position)
.unwrap_or(0);
if let Some(seg) = new_line_segs.get_mut(preserved_prefix_len + line_index) {
apply_inline_control_line_height(seg, height_hwp);
}
}
}
if split_stale_cell_reflow {
apply_reflowed_equation_row_metrics(
para,
&mut new_line_segs,
styles,
ls_type,
ls_value,
dpi,
);
}
let mut vpos = if preserved_prefix_len > 0 {
let last = &new_line_segs[preserved_prefix_len - 1];
last.vertical_pos
.saturating_add(last.line_height)
.saturating_add(last.line_spacing)
} else {
orig.as_ref().map(|ls| ls.vertical_pos).unwrap_or(0)
};
for i in preserved_prefix_len..new_line_segs.len() {
new_line_segs[i].vertical_pos = vpos;
vpos += new_line_segs[i].line_height + new_line_segs[i].line_spacing;
}
mark_indented_lines(
&mut new_line_segs[preserved_prefix_len..],
preserved_prefix_len,
para_style,
&original_line_segs,
seg_width_hwp,
);
let space_metrics =
storage.collect(new_line_segs.iter().enumerate().map(|(index, line)| {
let rule = if index < preserved_prefix_len {
para.line_space_metric(index)
} else {
reflow_space_metric
};
(line.text_start, rule)
}))?;
para.replace_line_segs_with_space_metrics(new_line_segs, space_metrics);
Ok(preserved_prefix_len > 0)
}
pub(crate) fn recalculate_section_vpos(
paragraphs: &mut [Paragraph],
start_para: usize,
ignore_reset_range: Option<std::ops::Range<usize>>,
start_stored_end: Option<i32>,
styles: &ResolvedStyleSet,
dpi: f64,
is_hwp3_variant: bool,
) {
if paragraphs.is_empty() || start_para >= paragraphs.len() {
return;
}
let boundary_gap = |prev: &Paragraph, curr: &Paragraph| -> i32 {
let spacing_after = styles
.para_styles
.get(prev.para_shape_id as usize)
.map(|style| style.spacing_after)
.unwrap_or(0.0);
let spacing_before = styles
.para_styles
.get(curr.para_shape_id as usize)
.map(|style| style.spacing_before)
.unwrap_or(0.0);
let spacing_before =
crate::renderer::hwp3_variant_flow_spacing_before(spacing_before, is_hwp3_variant);
px_to_hwpunit(spacing_after + spacing_before, dpi)
};
let seg_advance = |ls: &LineSeg| -> i32 {
let height = if ls.line_height > ls.text_height && ls.text_height > 0 {
ls.text_height
} else {
ls.line_height
};
height.saturating_add(ls.line_spacing)
};
let seg_end = |p: &Paragraph| -> Option<i32> {
p.line_segs
.last()
.map(|ls| ls.vertical_pos.saturating_add(seg_advance(ls)))
};
let is_ignored = |pi: usize| {
ignore_reset_range
.as_ref()
.is_some_and(|range| range.contains(&pi))
};
let mut prev_idx: Option<usize> = paragraphs[..start_para]
.iter()
.rposition(|p| !p.line_segs.is_empty());
let mut next_vpos = match prev_idx {
Some(pp) => seg_end(¶graphs[pp]).unwrap_or(0),
None => paragraphs[start_para]
.line_segs
.first()
.map(|ls| ls.vertical_pos)
.unwrap_or(0),
};
let mut orig_prev_first: Option<i32> = prev_idx
.and_then(|pp| paragraphs[pp].line_segs.first())
.map(|ls| ls.vertical_pos);
let mut orig_prev_end: Option<i32> = prev_idx.and_then(|pp| seg_end(¶graphs[pp]));
let mut prev_modified = false;
let mut prev_delta: i32 = 0;
let mut skipped_unlined = false;
let mut in_start_run = true;
let hosts_para_topbottom_object = |p: &Paragraph| {
p.controls.iter().any(|control| {
let common = match control {
Control::Table(table) => &table.common,
Control::Picture(picture) => &picture.common,
Control::Shape(shape) => shape.common(),
Control::Equation(equation) => &equation.common,
_ => return false,
};
crate::renderer::float_placement::is_para_topbottom_float(common)
})
};
for pi in start_para..paragraphs.len() {
if paragraphs[pi].line_segs.is_empty() {
skipped_unlined = true;
continue;
}
let para_modified = pi == start_para || is_ignored(pi);
let current_start = paragraphs[pi].line_segs[0].vertical_pos;
let is_original_lineseg =
paragraphs[pi].line_segs[0].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0;
let prev_stored_bound = if prev_idx == Some(start_para) && !is_ignored(start_para) {
start_stored_end.or(orig_prev_first)
} else if prev_modified {
orig_prev_first
} else {
orig_prev_end
};
let is_reset = is_original_lineseg
&& !is_ignored(pi)
&& prev_stored_bound.is_some_and(|bound| current_start < bound);
let delta = if is_reset {
0
} else if skipped_unlined && !para_modified {
let stored_prev_end = if prev_idx == Some(start_para) && !is_ignored(start_para) {
start_stored_end.or(orig_prev_end)
} else {
orig_prev_end
};
stored_prev_end.map_or(0, |end| next_vpos - end)
} else if para_modified || prev_modified {
let gap = prev_idx
.map(|pp| boundary_gap(¶graphs[pp], ¶graphs[pi]))
.unwrap_or(0);
let occupied = match start_stored_end {
Some(stored_end)
if !para_modified
&& in_start_run
&& is_original_lineseg
&& !is_ignored(start_para)
&& hosts_para_topbottom_object(¶graphs[pi]) =>
{
let stored_gap = boundary_gap(¶graphs[start_para], ¶graphs[pi]);
current_start
.saturating_sub(stored_end)
.saturating_sub(stored_gap)
.max(0)
}
_ => 0,
};
next_vpos.saturating_add(gap).saturating_add(occupied) - current_start
} else {
prev_delta
};
let orig_first = current_start;
let orig_end = seg_end(¶graphs[pi]);
if delta != 0 {
for seg in &mut paragraphs[pi].line_segs {
seg.vertical_pos = seg.vertical_pos.saturating_add(delta);
}
}
if let Some(end) = orig_end {
next_vpos = end.saturating_add(delta);
}
orig_prev_first = Some(orig_first);
orig_prev_end = orig_end;
prev_modified = para_modified;
prev_delta = delta;
prev_idx = Some(pi);
skipped_unlined = false;
if !para_modified {
in_start_run = false;
}
}
}
pub(crate) fn paragraph_flow_end(para: &Paragraph) -> Option<i32> {
para.line_segs.last().map(|ls| {
let height = if ls.line_height > ls.text_height && ls.text_height > 0 {
ls.text_height
} else {
ls.line_height
};
ls.vertical_pos
.saturating_add(height.saturating_add(ls.line_spacing))
})
}
fn font_size_to_line_height(font_size_px: f64, dpi: f64) -> i32 {
round_px_to_hwpunit(font_size_px, dpi)
}
fn round_px_to_hwpunit(px: f64, dpi: f64) -> i32 {
(px * 7_200.0 / dpi).round() as i32
}
fn compute_line_spacing_hwp(
ls_type: LineSpacingType,
ls_value: f64,
line_height_hwp: i32,
dpi: f64,
) -> i32 {
match ls_type {
LineSpacingType::Percent => {
if ls_value >= 0.0 {
let raw = line_height_hwp as f64 * (ls_value - 100.0) / 100.0;
((raw.abs() / 4.0 + 0.5).floor() * 4.0 * raw.signum()) as i32
} else {
0
}
}
LineSpacingType::Fixed => {
let fixed_hwp = round_px_to_hwpunit(ls_value, dpi);
(fixed_hwp - line_height_hwp).max(0)
}
LineSpacingType::SpaceOnly => {
round_px_to_hwpunit(ls_value, dpi)
}
LineSpacingType::Minimum => {
let min_hwp = round_px_to_hwpunit(ls_value, dpi);
(min_hwp - line_height_hwp).max(0)
}
}
}
#[cfg(test)]
mod fill_cursor_tests {
use super::*;
fn collect_one_interval_at_a_time(
tokens: &[BreakToken],
text_chars: &[char],
available_width_px: f64,
indent_px: f64,
default_tab_width: f64,
korean_break_unit: u8,
condense_min_space: u8,
initial_start_idx: usize,
initial_is_first_line: bool,
) -> Vec<LineBreakResult> {
let mut cursor = FillCursor::new(initial_start_idx, initial_is_first_line);
let mut results = Vec::new();
while let Some(result) = fill_one_interval(
tokens,
text_chars,
available_width_px,
indent_px,
TabFill::default_only(default_tab_width),
korean_break_unit,
condense_min_space,
&[],
&mut cursor,
None,
) {
results.push(result.line);
}
results
}
fn assert_cursor_matches_frozen_scalar(
tokens: &[BreakToken],
text_chars: &[char],
available_width_px: f64,
indent_px: f64,
default_tab_width: f64,
korean_break_unit: u8,
condense_min_space: u8,
initial_start_idx: usize,
initial_is_first_line: bool,
) -> Vec<LineBreakResult> {
let frozen = fill_lines_before_cursor(
tokens,
text_chars,
available_width_px,
indent_px,
default_tab_width,
korean_break_unit,
condense_min_space,
initial_start_idx,
initial_is_first_line,
);
let scalar = fill_lines(
tokens,
text_chars,
available_width_px,
indent_px,
TabFill::default_only(default_tab_width),
korean_break_unit,
condense_min_space,
&[],
initial_start_idx,
initial_is_first_line,
true,
None,
);
let resumed = collect_one_interval_at_a_time(
tokens,
text_chars,
available_width_px,
indent_px,
default_tab_width,
korean_break_unit,
condense_min_space,
initial_start_idx,
initial_is_first_line,
);
assert_eq!(scalar, frozen);
assert_eq!(resumed, frozen);
frozen
}
fn assert_overflowing_object_space_moves_with_its_visible_object() {
let chars = ['a', ' ', 'b'];
let text = |start_idx, end_idx| BreakToken::Text {
start_idx,
end_idx,
base_width: 10.0,
width: 10.0,
max_font_size: 12.0,
base_char_widths: vec![10.0],
char_widths: vec![10.0],
};
let tokens = [
text(0, 1),
BreakToken::Space {
idx: 1,
width: 20.0,
condense_base: 20.0,
max_font_size: 12.0,
inline_width: 20.0,
},
text(2, 3),
];
let lines = collect_one_interval_at_a_time(&tokens, &chars, 25.0, 0.0, 48.0, 0, 0, 0, true);
assert_eq!(
lines
.iter()
.map(|l| (l.start_idx, l.end_idx))
.collect::<Vec<_>>(),
vec![(0, 1), (1, 2), (2, 3)]
);
let tokens = [
text(0, 1),
BreakToken::Space {
idx: 1,
width: 20.0,
condense_base: 8.0,
max_font_size: 12.0,
inline_width: 12.0,
},
text(2, 3),
];
let lines = collect_one_interval_at_a_time(&tokens, &chars, 25.0, 0.0, 48.0, 0, 0, 0, true);
assert_eq!(
lines
.iter()
.map(|l| (l.start_idx, l.end_idx))
.collect::<Vec<_>>(),
vec![(0, 2), (2, 3)]
);
}
#[test]
fn cursor_resumes_a_long_text_token_at_each_interval() {
let text_chars = "abcdefghij".chars().collect::<Vec<_>>();
let tokens = vec![BreakToken::Text {
start_idx: 0,
end_idx: text_chars.len(),
base_width: 100.0,
width: 100.0,
max_font_size: 12.0,
base_char_widths: vec![10.0; text_chars.len()],
char_widths: vec![10.0; text_chars.len()],
}];
let results = assert_cursor_matches_frozen_scalar(
&tokens,
&text_chars,
25.0,
0.0,
48.0,
0,
0,
0,
true,
);
assert_eq!(
results
.iter()
.map(|result| (result.start_idx, result.end_idx, result.has_line_break))
.collect::<Vec<_>>(),
vec![
(0, 2, false),
(2, 4, false),
(4, 6, false),
(6, 8, false),
(8, 10, false),
]
);
}
#[test]
fn cursor_preserves_scalar_space_tab_and_forced_break_results() {
assert_overflowing_object_space_moves_with_its_visible_object();
let text_chars = "ab c\td\nxy".chars().collect::<Vec<_>>();
let tokens = vec![
BreakToken::Text {
start_idx: 0,
end_idx: 2,
base_width: 20.0,
width: 20.0,
max_font_size: 12.0,
base_char_widths: vec![10.0, 10.0],
char_widths: vec![10.0, 10.0],
},
BreakToken::Space {
idx: 2,
width: 5.0,
condense_base: 5.0,
max_font_size: 12.0,
inline_width: 0.0,
},
BreakToken::Text {
start_idx: 3,
end_idx: 4,
base_width: 10.0,
width: 10.0,
max_font_size: 12.0,
base_char_widths: vec![10.0],
char_widths: vec![10.0],
},
BreakToken::Tab {
idx: 4,
max_font_size: 12.0,
auto_left_target: None,
},
BreakToken::Text {
start_idx: 5,
end_idx: 6,
base_width: 10.0,
width: 10.0,
max_font_size: 12.0,
base_char_widths: vec![10.0],
char_widths: vec![10.0],
},
BreakToken::LineBreak { idx: 6 },
BreakToken::Text {
start_idx: 7,
end_idx: 9,
base_width: 20.0,
width: 20.0,
max_font_size: 12.0,
base_char_widths: vec![10.0, 10.0],
char_widths: vec![10.0, 10.0],
},
];
let actual =
collect_one_interval_at_a_time(&tokens, &text_chars, 24.0, 0.0, 48.0, 0, 0, 0, true);
assert_eq!(
actual
.iter()
.map(|l| (l.start_idx, l.end_idx, l.has_line_break))
.collect::<Vec<_>>(),
vec![
(0, 3, false),
(3, 4, false),
(4, 5, false),
(5, 7, true),
(7, 9, false)
]
);
let before = fill_lines_before_cursor(&tokens, &text_chars, 24.0, 0.0, 48.0, 0, 0, 0, true);
assert_ne!(
actual, before,
"the frozen filler deferred the overflowing space"
);
}
}
#[cfg(test)]
mod frame_reflow_tests {
use super::*;
use crate::renderer::layout_frame::{FrameExclusion, FrameExclusionPolicy};
use crate::renderer::style_resolver::{ResolvedCharStyle, ResolvedParaStyle};
fn styles(font_sizes: &[f64]) -> ResolvedStyleSet {
ResolvedStyleSet {
char_styles: font_sizes
.iter()
.map(|font_size| ResolvedCharStyle {
font_size: *font_size,
ratio: 1.0,
..Default::default()
})
.collect(),
para_styles: vec![ResolvedParaStyle::default()],
..Default::default()
}
}
fn paragraph(text: &str, char_shapes: Vec<CharShapeRef>) -> Paragraph {
Paragraph {
text: text.to_string(),
char_offsets: text
.chars()
.scan(0u32, |offset, character| {
let current = *offset;
*offset += character.len_utf16() as u32;
Some(current)
})
.collect(),
char_count: text.encode_utf16().count() as u32 + 1,
char_shapes,
..Default::default()
}
}
fn shared_metrics(lines: &[LineSeg]) -> Vec<(i32, i32, i32, i32, i32)> {
lines
.iter()
.map(|line| {
(
line.vertical_pos,
line.line_height,
line.text_height,
line.baseline_distance,
line.line_spacing,
)
})
.collect()
}
fn line_fields(lines: &[LineSeg]) -> Vec<(u32, i32, i32, i32, i32, i32, i32, i32, u32)> {
lines
.iter()
.map(|line| {
(
line.text_start,
line.vertical_pos,
line.line_height,
line.text_height,
line.baseline_distance,
line.line_spacing,
line.column_start,
line.segment_width,
line.tag,
)
})
.collect()
}
fn frozen_scalar_projection(
para: &Paragraph,
available_width_px: f64,
styles: &ResolvedStyleSet,
dpi: f64,
) -> Vec<LineSeg> {
let text_chars = para.text.chars().collect::<Vec<_>>();
let style = styles.para_styles.get(para.para_shape_id as usize);
let indent_px = style.map(|value| value.indent).unwrap_or(0.0);
let english_break_unit = style.map(|value| value.english_break_unit).unwrap_or(0);
let korean_break_unit = style.map(|value| value.korean_break_unit).unwrap_or(0);
let condense_min_space = style.map(|value| value.condense_min_space).unwrap_or(0);
let default_tab_width = style.map(|value| value.default_tab_width).unwrap_or(0.0);
let line_spacing_type = style
.map(|value| value.line_spacing_type)
.unwrap_or(LineSpacingType::Percent);
let line_spacing_value = style.map(|value| value.line_spacing).unwrap_or(160.0);
let tokens = tokenize_paragraph_with_regenerated_space_metric(
&text_chars,
¶.char_offsets,
¶.char_shapes,
styles,
english_break_unit,
korean_break_unit,
SpaceMetric::Stored,
&[],
para.control_mask & (1 << 0x18) != 0,
¶.literal_figure_spaces,
);
let line_breaks = fill_lines_before_cursor(
&tokens,
&text_chars,
available_width_px,
indent_px,
default_tab_width,
korean_break_unit,
condense_min_space,
0,
true,
);
let segment_width = px_to_hwpunit(available_width_px, dpi);
let source_tag = para
.line_segs
.first()
.map(|line| line.tag)
.unwrap_or(LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY);
let mut vertical_pos = para
.line_segs
.first()
.map(|line| line.vertical_pos)
.unwrap_or(0);
line_breaks
.iter()
.enumerate()
.map(|(index, line)| {
let font_size = if line.max_font_size > 0.0 {
line.max_font_size
} else {
12.0
};
let line_height = font_size_to_line_height(font_size, dpi);
let line_spacing = compute_line_spacing_hwp(
line_spacing_type,
line_spacing_value,
line_height,
dpi,
);
let projected = LineSeg {
text_start: if index == 0 {
0
} else {
char_index_to_utf16_offset(para, line.start_idx)
},
vertical_pos,
line_height,
text_height: line_height,
baseline_distance: baseline_distance_hwp(line_height),
line_spacing,
column_start: 0,
segment_width,
tag: if source_tag == 0 {
LineSeg::TAG_SINGLE_SEGMENT_LINE
} else {
source_tag
},
};
vertical_pos += line_height + line_spacing;
projected
})
.collect()
}
#[test]
fn frame_reflow_projects_two_intervals_as_one_physical_row() {
let styles = styles(&[12.0]);
let para = paragraph(
"abcdef ghijkl",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
let mut frame = LayoutFrame::new(
0..9_000,
100,
vec![FrameExclusion {
horizontal: 3_000..5_000,
vertical: 0..10_000,
policy: FrameExclusionPolicy::BothSides,
}],
);
let lines = layout_paragraph_in_frame(¶, &mut frame, &styles, 96.0)
.expect("two usable intervals accept scalar text");
assert_eq!(lines.len(), 2);
assert_eq!(
lines.iter().map(|line| line.text_start).collect::<Vec<_>>(),
vec![0, 7]
);
assert_eq!(
lines
.iter()
.map(|line| (line.column_start, line.segment_width))
.collect::<Vec<_>>(),
vec![(0, 3_000), (5_000, 4_000)]
);
assert_eq!(shared_metrics(&lines), vec![(100, 900, 900, 765, 540); 2]);
assert!(lines[0].is_first_segment());
assert!(!lines[0].is_last_segment());
assert!(!lines[1].is_first_segment());
assert!(lines[1].is_last_segment());
assert_eq!(frame.row_count(), 1);
assert_eq!(frame.top, 1_540);
}
#[test]
fn frame_reflow_retries_a_taller_row_without_consuming_the_cursor() {
a_frame_that_expects_the_stored_rows_admits_them_and_skips_the_reflow();
width_neutrality_is_a_property_of_geometry_not_a_list_of_variants();
body_stored_route_admits_only_width_neutral_structural_controls();
hwp3_formatting_rebuild_preserves_legacy_stored_geometry_jurisdiction();
frame_rejected_rows_reflow_without_propagating_cached_source_flags();
picture_band_frame_fill_inherits_provenance_not_cached_row_state();
let styles = styles(&[12.0, 20.0]);
let para = paragraph(
"abcdef ghijk",
vec![
CharShapeRef {
start_pos: 0,
char_shape_id: 0,
},
CharShapeRef {
start_pos: 7,
char_shape_id: 1,
},
],
);
let mut frame = LayoutFrame::new(
0..9_000,
0,
vec![FrameExclusion {
horizontal: 4_000..5_000,
vertical: 1_000..5_000,
policy: FrameExclusionPolicy::BothSides,
}],
);
let lines = layout_paragraph_in_frame(¶, &mut frame, &styles, 96.0)
.expect("the taller retry restores the first interval's cursor");
assert_eq!(lines.len(), 2);
assert_eq!(
lines.iter().map(|line| line.text_start).collect::<Vec<_>>(),
vec![0, 7]
);
assert_eq!(
lines
.iter()
.map(|line| (line.column_start, line.segment_width))
.collect::<Vec<_>>(),
vec![(0, 4_000), (5_000, 4_000)]
);
assert_eq!(
shared_metrics(&lines),
vec![(0, 1_500, 1_500, 1_275, 900); 2]
);
assert_eq!(frame.row_count(), 1);
assert_eq!(frame.top, 2_400);
}
fn a_frame_that_expects_the_stored_rows_admits_them_and_skips_the_reflow() {
let styles = styles(&[12.0]);
let mut para = paragraph(
"alpha beta gamma delta",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
para.line_segs = vec![
LineSeg {
text_start: 0,
vertical_pos: 700,
line_height: 321,
text_height: 300,
baseline_distance: 250,
line_spacing: 17,
column_start: 1_000,
segment_width: 4_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
},
LineSeg {
text_start: 2,
vertical_pos: 1_038,
line_height: 654,
text_height: 600,
baseline_distance: 500,
line_spacing: 23,
column_start: 1_000,
segment_width: 4_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
},
];
let mut frame = LayoutFrame::new(1_000..5_000, 700, Vec::new());
let resolution = resolve_stored_line_segs_in_frame(
¶,
&mut frame,
&styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
)
.expect("a scalar cached paragraph is frame-resolvable");
assert_eq!(resolution, StoredRowResolution::Stored);
assert_eq!(frame.row_count(), 2);
let projected = frame.project_line_segs();
assert_eq!(projected.len(), 2);
assert!(projected
.iter()
.zip(¶.line_segs)
.all(|(row, stored)| row.text_start == stored.text_start
&& row.column_start == stored.column_start
&& row.segment_width == stored.segment_width));
let computed = frame_metrics_for_line(12.0, 12.0, LineSpacingType::Percent, 160.0, 96.0);
assert!(projected
.iter()
.all(|row| row.line_height == computed.line_height
&& row.line_spacing == computed.line_spacing));
assert_eq!(
frame.top,
700 + 2 * (computed.line_height + computed.line_spacing)
);
}
fn width_neutrality_is_a_property_of_geometry_not_a_list_of_variants() {
for control in [
Control::SectionDef(Box::default()),
Control::ColumnDef(Default::default()),
Control::Field(Default::default()),
Control::Bookmark(Default::default()),
Control::PageNumberPos(Default::default()),
Control::PageHide(Default::default()),
Control::HiddenComment(Box::default()),
Control::Hyperlink(Default::default()),
Control::AutoNumber(Default::default()),
Control::NewNumber(Default::default()),
Control::Unknown(Default::default()),
] {
assert!(
control_is_width_neutral_marker(&control),
"{control:?} has no geometry, so the frame must own its paragraph"
);
}
for control in [
Control::Table(Box::default()),
Control::Shape(Box::new(crate::model::shape::ShapeObject::Rectangle(
Default::default(),
))),
Control::Picture(Box::default()),
Control::Equation(Box::default()),
Control::Form(Box::default()),
Control::Header(Box::default()),
Control::Footer(Box::default()),
Control::Footnote(Box::default()),
Control::Endnote(Box::default()),
] {
assert!(
!control_is_width_neutral_marker(&control),
"{control:?} owns its own layout box"
);
}
}
fn body_stored_route_admits_only_width_neutral_structural_controls() {
let styles = styles(&[12.0]);
let mut structural = paragraph(
"section body",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
structural.line_segs = vec![LineSeg {
vertical_pos: 100,
line_height: 900,
text_height: 900,
baseline_distance: 765,
line_spacing: 540,
column_start: 0,
segment_width: 9_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..Default::default()
}];
structural.controls = vec![
Control::SectionDef(Box::default()),
Control::ColumnDef(Default::default()),
];
assert!(supports_cached_body_frame_controls(&structural));
let mut structural_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
assert!(matches!(
resolve_stored_line_segs_in_frame(
&structural,
&mut structural_frame,
&styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
),
Some(StoredRowResolution::Stored)
));
assert_eq!(structural_frame.row_count(), 1);
assert_eq!(
structural_frame
.project_line_segs()
.iter()
.map(|line| (line.column_start, line.segment_width))
.collect::<Vec<_>>(),
vec![(0, 9_000)]
);
let mut specialized = structural.clone();
specialized.controls = vec![Control::Table(Box::default())];
assert!(!supports_cached_body_frame_controls(&specialized));
let mut specialized_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
let checkpoint = specialized_frame.clone();
assert!(resolve_stored_line_segs_in_frame(
&specialized,
&mut specialized_frame,
&styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
true,
&[],
false,
)
.is_none());
assert_eq!(specialized_frame, checkpoint);
let mut varying_single_slot = structural.clone();
varying_single_slot.controls.clear();
varying_single_slot.line_segs = vec![
LineSeg {
text_start: 0,
column_start: 0,
segment_width: 4_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..structural.line_segs[0].clone()
},
LineSeg {
text_start: 4,
column_start: 0,
segment_width: 9_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..structural.line_segs[0].clone()
},
];
let mut scalar_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
let scalar_checkpoint = scalar_frame.clone();
assert!(resolve_stored_line_segs_in_frame(
&varying_single_slot,
&mut scalar_frame,
&styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
)
.is_none());
assert_eq!(scalar_frame, scalar_checkpoint);
let mut empty_external_carrier = structural.clone();
empty_external_carrier.text.clear();
empty_external_carrier.char_offsets.clear();
empty_external_carrier.char_count = 1;
empty_external_carrier.controls.clear();
empty_external_carrier.line_segs = vec![LineSeg {
text_start: 0,
column_start: 4_000,
segment_width: 5_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..structural.line_segs[0].clone()
}];
let mut carrier_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
let carrier_checkpoint = carrier_frame.clone();
assert!(resolve_stored_line_segs_in_frame(
&empty_external_carrier,
&mut carrier_frame,
&styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
)
.is_none());
assert_eq!(carrier_frame, carrier_checkpoint);
}
fn hwp3_formatting_rebuild_preserves_legacy_stored_geometry_jurisdiction() {
use crate::document_core::DocumentCore;
use std::fs;
use std::path::Path;
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("samples/issue1892_hwp3_drawing_group_roundtrip.hwp");
let bytes = fs::read(&path).unwrap_or_else(|error| panic!("read {path:?}: {error}"));
let mut core = DocumentCore::from_bytes(&bytes).expect("load HWP3 formatting fixture");
assert!(
core.document.layout_profile().legacy_hwp3_stored_geometry(),
"the HWP3 fixture must retain legacy stored-geometry jurisdiction"
);
let (section_index, paragraph_index) = core
.document
.sections
.iter()
.enumerate()
.find_map(|(section_index, section)| {
section
.paragraphs
.iter()
.enumerate()
.find(|(_, paragraph)| {
!paragraph.text.trim().is_empty()
&& paragraph.controls.is_empty()
&& paragraph.line_segs.len() == 1
&& paragraph.line_segs[0].is_first_segment()
&& paragraph.line_segs[0].is_last_segment()
&& paragraph.line_segs[0].segment_width > 2_400
})
.map(|(paragraph_index, _)| (section_index, paragraph_index))
})
.expect("fixture has a plain legacy stored row");
let stored_before = line_fields(
&core.document.sections[section_index].paragraphs[paragraph_index].line_segs,
);
core.apply_char_format_native(
section_index,
paragraph_index,
0,
1,
r#"{"underline":true}"#,
)
.expect("apply paint-only format");
assert_eq!(
line_fields(
&core.document.sections[section_index].paragraphs[paragraph_index].line_segs,
),
stored_before
);
assert!(core.document.layout_profile().legacy_hwp3_stored_geometry());
let paragraph = &core.document.sections[section_index].paragraphs[paragraph_index];
let stored = ¶graph.line_segs[0];
let frame_horizontal = stored.column_start.saturating_add(1_200)
..stored.column_start.saturating_add(stored.segment_width);
let mut ordinary_frame =
LayoutFrame::new(frame_horizontal.clone(), stored.vertical_pos, Vec::new());
assert!(matches!(
resolve_stored_line_segs_in_frame(
paragraph,
&mut ordinary_frame,
&core.styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
),
Some(StoredRowResolution::Reflowed)
));
let mut legacy_frame = LayoutFrame::new(frame_horizontal, stored.vertical_pos, Vec::new());
assert!(
resolve_stored_line_segs_in_frame(
paragraph,
&mut legacy_frame,
&core.styles,
96.0,
true,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
)
.is_none(),
"untouched HWP3 stored origin remains outside the common Frame's jurisdiction"
);
}
fn frame_rejected_rows_reflow_without_propagating_cached_source_flags() {
let styles = styles(&[12.0]);
let mut para = paragraph(
"abcdef ghijkl",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
para.line_segs = vec![LineSeg {
text_start: 0,
vertical_pos: 100,
line_height: 900,
text_height: 900,
baseline_distance: 765,
line_spacing: 540,
column_start: 0,
segment_width: 9_000,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE
| LineSeg::TAG_FIRST_LINE_OF_PAGE
| LineSeg::TAG_FIRST_LINE_OF_COLUMN
| LineSeg::TAG_EMPTY_SEGMENT,
}];
let mut frame = LayoutFrame::new(
0..9_000,
100,
vec![FrameExclusion {
horizontal: 3_000..5_000,
vertical: 0..10_000,
policy: FrameExclusionPolicy::BothSides,
}],
);
let resolution = resolve_stored_line_segs_in_frame(
¶,
&mut frame,
&styles,
96.0,
false,
StoredRowMissPolicy::Reflow,
false,
&[],
false,
)
.expect("a scalar cached paragraph is frame-resolvable");
let StoredRowResolution::Reflowed = resolution else {
panic!("rows differing from the frame expectation must reflow");
};
let lines = frame.project_line_segs();
assert_eq!(
lines
.iter()
.map(|line| (line.text_start, line.column_start, line.segment_width))
.collect::<Vec<_>>(),
vec![(0, 0, 3_000), (7, 5_000, 4_000)]
);
assert_eq!(frame.row_count(), 1);
assert_eq!(frame.top, 1_540);
let rejected_cache_flags = LineSeg::TAG_FIRST_LINE_OF_PAGE
| LineSeg::TAG_FIRST_LINE_OF_COLUMN
| LineSeg::TAG_EMPTY_SEGMENT;
assert!(lines
.iter()
.all(|line| line.tag & rejected_cache_flags == 0));
assert!(lines
.iter()
.all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0));
}
fn picture_band_frame_fill_inherits_provenance_not_cached_row_state() {
let styles = styles(&[12.0]);
let mut para = paragraph(
"alpha beta gamma delta epsilon zeta eta theta iota kappa",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
let cached_row_flags = LineSeg::TAG_FIRST_LINE_OF_PAGE
| LineSeg::TAG_FIRST_LINE_OF_COLUMN
| LineSeg::TAG_EMPTY_SEGMENT
| LineSeg::TAG_AUTO_HYPHENATION
| LineSeg::TAG_INDENTATION
| LineSeg::TAG_PARAGRAPH_HEAD;
para.line_segs = vec![LineSeg {
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE | cached_row_flags,
..Default::default()
}];
let fill = |paragraph: &Paragraph| {
let mut frame = LayoutFrame::new(0..3_000, 0, Vec::new());
layout_paragraph_in_frame(paragraph, &mut frame, &styles, 96.0)
.expect("Picture-band fill must produce fresh rows")
};
let mut picture_band_input = para;
picture_band_input.line_segs.clear();
let synthetic = fill(&picture_band_input);
assert!(synthetic.len() > 1, "fixture must exercise later rows");
assert!(synthetic
.iter()
.all(|line| line.tag & cached_row_flags == 0));
assert!(synthetic
.iter()
.all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0));
}
#[test]
fn eligible_scalar_reflow_projects_the_frozen_scalar_oracle() {
let styles = styles(&[12.0]);
let mut para = paragraph(
"alpha beta gamma delta epsilon",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
para.line_segs = vec![LineSeg {
vertical_pos: 321,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY,
..Default::default()
}];
let mut expected = frozen_scalar_projection(¶, 50.0, &styles, 96.0);
assert!(expected.len() > 1, "fixture must exercise row recurrence");
for line in &mut expected {
line.segment_width -= line.segment_width.rem_euclid(4);
}
reflow_line_segs(
&mut para,
ParagraphBox::content_width_px(50.0, 96.0),
&styles,
96.0,
);
assert_eq!(line_fields(¶.line_segs), line_fields(&expected));
assert!(para
.line_segs
.iter()
.all(|line| line.segment_width == 3_748 && line.column_start == 0));
assert_eq!(para.line_segs[0].vertical_pos, 321);
}
#[test]
fn picture_band_uses_para_reference_not_text_frame_for_right_aligned_picture() {
use crate::model::image::Picture;
use crate::model::shape::{HorzAlign, HorzRelTo, TextFlow, TextWrap, VertAlign, VertRelTo};
const DPI: f64 = 96.0;
const COLUMN_WIDTH: i32 = 15_000;
const MARGIN_LEFT: i32 = 1_500;
const MARGIN_RIGHT: i32 = 3_000;
const PICTURE_WIDTH: u32 = 3_000;
let mut styles = styles(&[12.0]);
styles.para_styles[0].margin_left = crate::renderer::hwpunit_to_px(MARGIN_LEFT, DPI);
styles.para_styles[0].margin_right = crate::renderer::hwpunit_to_px(MARGIN_RIGHT, DPI);
let text_frame = MARGIN_LEFT..COLUMN_WIDTH - MARGIN_RIGHT;
let paragraph_reference = picture_band_paragraph_reference(&(0..COLUMN_WIDTH), MARGIN_LEFT)
.expect("host left margin leaves a usable Paragraph reference");
assert_eq!(paragraph_reference, MARGIN_LEFT..COLUMN_WIDTH);
assert_ne!(text_frame, paragraph_reference);
let picture = Picture {
common: crate::model::shape::CommonObjAttr {
width: PICTURE_WIDTH,
height: 600,
text_wrap: TextWrap::Square,
text_flow: TextFlow::BothSides,
vert_rel_to: VertRelTo::Para,
vert_align: VertAlign::Top,
horz_rel_to: HorzRelTo::Para,
horz_align: HorzAlign::Right,
..Default::default()
},
..Default::default()
};
let expected_exclusion = crate::renderer::float_placement::resolve_picture_exclusion(
&picture,
0..COLUMN_WIDTH,
paragraph_reference.clone(),
0,
crate::renderer::float_placement::PaperOrigin::default(),
)
.expect("supported Paragraph-relative Picture");
assert_eq!(expected_exclusion.horizontal, 12_000..15_000);
let mut host = paragraph(
"x",
vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
);
host.controls.push(Control::Picture(Box::new(picture)));
let band = layout_picture_band(
&[host],
0,
crate::renderer::hwpunit_to_px(COLUMN_WIDTH, DPI),
&styles,
DPI,
(0.0, 0.0),
)
.expect("the one-row Paragraph-relative Picture band");
assert_eq!(band.paragraph_range, 0..1);
assert_eq!(band.line_segs[0].len(), 1);
assert_eq!(band.line_segs[0][0].column_start, text_frame.start);
assert_eq!(
band.line_segs[0][0].segment_width,
text_frame.end - text_frame.start,
"the right-aligned Para exclusion begins at the text frame's end"
);
}
#[test]
fn pic2_two_picture_host_is_explicitly_outside_the_one_picture_band_contract() {
use crate::model::page::ColumnDef;
use crate::renderer::page_layout::PageLayoutInfo;
const DPI: f64 = 96.0;
let bytes = std::fs::read(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("samples/pic2.hwp"),
)
.expect("pic2 fixture");
let document = crate::parse_document(&bytes).expect("parse pic2 fixture");
let section = &document.sections[0];
let column_def = section.paragraphs[..=0]
.iter()
.flat_map(|paragraph| ¶graph.controls)
.filter_map(|control| match control {
Control::ColumnDef(column) => Some(column.clone()),
_ => None,
})
.next_back()
.unwrap_or_else(ColumnDef::default);
let page_layout =
PageLayoutInfo::from_page_def(§ion.section_def.page_def, &column_def, DPI);
let column_width = page_layout.column_areas[0].width;
let styles = crate::renderer::style_resolver::resolve_styles(&document.doc_info, DPI);
assert_eq!(
section.paragraphs[0]
.controls
.iter()
.filter(|control| {
matches!(control, Control::Picture(picture) if !picture.common.treat_as_char)
})
.count(),
2,
"fixture premise: pic2's first paragraph has two floating pictures"
);
assert!(
layout_picture_band(
§ion.paragraphs,
0,
column_width,
&styles,
DPI,
(0.0, 0.0)
)
.is_none(),
"two floating pictures are deliberately not a one-picture band"
);
}
}
#[cfg(test)]
mod utf16_offset_tests {
use super::*;
#[test]
fn trailing_physical_line_preserves_control_stream_end_offset() {
let mut para = Paragraph {
text: "가\n".to_string(),
char_offsets: vec![16, 17],
..Default::default()
};
reflow_line_segs(
&mut para,
ParagraphBox::content_width_px(500.0, 96.0),
&ResolvedStyleSet::default(),
96.0,
);
assert_eq!(para.line_segs.len(), 2);
assert_eq!(para.line_segs[1].text_start, 18);
}
#[test]
fn missing_char_offsets_count_supplementary_unicode_as_utf16_units() {
let para = Paragraph {
text: "😀\n".to_string(),
..Default::default()
};
assert_eq!(char_index_to_utf16_offset(¶, 2), 3);
}
}