use std::cell::RefCell;
use crate::model::document::{DocInfo, Document};
use crate::model::paragraph::{ColumnBreakType, Paragraph};
use crate::model::style::HeadType;
use crate::doclang::ir::prov::Prov;
use crate::doclang::ir::{Block, ListItem};
use crate::doclang::loss::report::{LossEntry, LossKind, LossReport};
use crate::doclang::options::Mode;
use super::control::{self, ControlCtx, ControlOutcome};
use super::resources;
pub(crate) fn convert_paragraph(
para: &Paragraph,
document: &Document,
doc_info: &DocInfo,
mode: Mode,
footnote_counter: &mut usize,
location: &str,
loss: &mut LossReport,
) -> Vec<Block> {
convert_paragraph_prov(
para,
document,
doc_info,
mode,
footnote_counter,
location,
loss,
None,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn convert_paragraph_prov(
para: &Paragraph,
document: &Document,
doc_info: &DocInfo,
mode: Mode,
footnote_counter: &mut usize,
location: &str,
loss: &mut LossReport,
body_pos: Option<(usize, usize)>,
) -> Vec<Block> {
let mut blocks: Vec<Block> = Vec::new();
let text_prov = body_pos.map(|(s, p)| Prov::text(s, p));
if para.column_type == ColumnBreakType::Page {
blocks.push(Block::PageBreak);
}
let head_type = resources::para_shape(doc_info, para.para_shape_id).map(|ps| ps.head_type);
match head_type {
None | Some(HeadType::None) => {
interleave_ordinary(
para,
document,
doc_info,
mode,
footnote_counter,
location,
loss,
&mut blocks,
body_pos,
text_prov,
);
}
Some(ht) => {
let inlines = super::inline::extract_inlines(para, doc_info, location, loss);
if !inlines.is_empty() {
let block = match ht {
HeadType::Outline => {
let para_level = resources::para_shape(doc_info, para.para_shape_id)
.map(|ps| ps.para_level)
.unwrap_or(0);
let raw_level = para_level as u16 + 1;
let level = raw_level.clamp(1, 6) as u8;
if raw_level > 6 {
loss.push(LossEntry {
kind: LossKind::Other("heading-level-clamped".to_string()),
location: location.to_string(),
detail: format!(
"outline level {} clamped to {} (DocLang headings are 1–6)",
raw_level, level
),
});
}
Block::Heading {
level,
content: inlines,
lost: None,
prov: text_prov,
}
}
HeadType::Number => single_item_list(true, inlines, text_prov),
HeadType::Bullet => single_item_list(false, inlines, text_prov),
HeadType::None => unreachable!("None handled in the other match arm"),
};
blocks.push(block);
}
if !para.controls.is_empty() {
for group in build_control_groups(
para,
document,
doc_info,
mode,
footnote_counter,
location,
loss,
body_pos,
) {
blocks.extend(group);
}
}
}
}
blocks
}
#[allow(clippy::too_many_arguments)]
fn interleave_ordinary(
para: &Paragraph,
document: &Document,
doc_info: &DocInfo,
mode: Mode,
footnote_counter: &mut usize,
location: &str,
loss: &mut LossReport,
blocks: &mut Vec<Block>,
body_pos: Option<(usize, usize)>,
text_prov: Option<Prov>,
) {
let char_len = para.text.chars().count();
let groups = if para.controls.is_empty() {
Vec::new()
} else {
build_control_groups(
para,
document,
doc_info,
mode,
footnote_counter,
location,
loss,
body_pos,
)
};
let positions = if para.controls.is_empty() {
Vec::new()
} else {
para.control_text_positions()
};
let mut placed: Vec<(usize, Vec<Block>)> = Vec::new();
let mut trailing: Vec<Block> = Vec::new();
for (ci, g) in groups.into_iter().enumerate() {
if g.is_empty() {
continue;
}
if group_is_flow(&g) {
let pos = positions.get(ci).copied().unwrap_or(char_len).min(char_len);
placed.push((pos, g));
} else {
trailing.extend(g);
}
}
placed.sort_by_key(|(p, _)| *p);
let mut cuts: Vec<usize> = placed.iter().map(|(p, _)| *p).collect();
cuts.dedup();
let segments = super::inline::extract_inline_segments(para, doc_info, location, loss, &cuts);
let mut pi = 0usize;
for (k, seg) in segments.into_iter().enumerate() {
if !seg.is_empty() {
blocks.push(Block::Paragraph {
content: seg,
lost: None,
prov: text_prov,
});
}
if k < cuts.len() {
let pos = cuts[k];
while pi < placed.len() && placed[pi].0 == pos {
blocks.append(&mut placed[pi].1);
pi += 1;
}
}
}
while pi < placed.len() {
blocks.append(&mut placed[pi].1);
pi += 1;
}
blocks.append(&mut trailing);
}
fn group_is_flow(group: &[Block]) -> bool {
!group.is_empty()
&& group.iter().all(|b| {
matches!(
b,
Block::Table(_) | Block::Picture { .. } | Block::Formula(_)
)
})
}
#[allow(clippy::too_many_arguments)]
fn build_control_groups(
para: &Paragraph,
document: &Document,
doc_info: &DocInfo,
mode: Mode,
footnote_counter: &mut usize,
location: &str,
loss: &mut LossReport,
body_pos: Option<(usize, usize)>,
) -> Vec<Vec<Block>> {
let loss_cell = RefCell::new(loss);
let convert_paras = |paras: &[Paragraph]| -> Vec<Block> {
let mut scratch = LossReport::new();
let out = convert_paragraphs(paras, document, doc_info, mode, location, &mut scratch);
loss_cell.borrow_mut().merge(scratch);
out
};
let convert_tbl = |t: &crate::model::table::Table| {
let mut scratch = LossReport::new();
let out = super::table::convert_table(t, doc_info, location, &convert_paras, &mut scratch);
loss_cell.borrow_mut().merge(scratch);
out
};
let resolve_pic = |bin_data_id: u16| -> Option<(Vec<u8>, String)> {
resources::bin_data_bytes(document, bin_data_id)
.map(|(bytes, ext)| (bytes, ext.to_string()))
};
let ctx = ControlCtx {
mode,
location,
convert_paragraphs: &convert_paras,
convert_table: &convert_tbl,
resolve_picture: &resolve_pic,
};
let mut groups: Vec<Vec<Block>> = Vec::with_capacity(para.controls.len());
for (ci, ctrl) in para.controls.iter().enumerate() {
let mut scratch = LossReport::new();
let outcome = control::convert_control(ctrl, &ctx, *footnote_counter, &mut scratch);
loss_cell.borrow_mut().merge(scratch);
match outcome {
ControlOutcome::Blocks(mut bs) => {
bump_footnote_counter(&bs, footnote_counter);
if let Some((section, para_idx)) = body_pos {
let prov = Prov::object(section, para_idx, ci);
for b in &mut bs {
stamp_object_prov(b, prov);
}
}
groups.push(bs);
}
ControlOutcome::SectionMarker | ControlOutcome::ColumnMarker { .. } => {
groups.push(Vec::new());
}
}
}
groups
}
pub(crate) fn convert_paragraphs(
paras: &[Paragraph],
document: &Document,
doc_info: &DocInfo,
mode: Mode,
location: &str,
loss: &mut LossReport,
) -> Vec<Block> {
let mut footnote_counter = 1usize;
let mut raw: Vec<Block> = Vec::new();
for (i, para) in paras.iter().enumerate() {
let para_loc = format!("{}/p{}", location, i);
raw.extend(convert_paragraph(
para,
document,
doc_info,
mode,
&mut footnote_counter,
¶_loc,
loss,
));
}
group_lists(raw)
}
fn single_item_list(
ordered: bool,
content: Vec<crate::doclang::ir::Inline>,
prov: Option<Prov>,
) -> Block {
Block::List {
ordered,
items: vec![ListItem {
content: vec![Block::Paragraph {
content,
lost: None,
prov,
}],
}],
lost: None,
prov,
}
}
fn stamp_object_prov(block: &mut Block, prov: Prov) {
match block {
Block::Table(t) => t.prov = Some(prov),
Block::Formula(f) => f.prov = Some(prov),
Block::Picture { prov: p, .. }
| Block::Footnote { prov: p, .. }
| Block::PageHeader { prov: p, .. }
| Block::PageFooter { prov: p, .. } => *p = Some(prov),
_ => {}
}
}
pub(crate) fn group_section_lists(blocks: Vec<Block>) -> Vec<Block> {
group_lists(blocks)
}
fn is_column_chunk_break(column_type: ColumnBreakType) -> bool {
matches!(
column_type,
ColumnBreakType::Column | ColumnBreakType::MultiColumn
)
}
pub(crate) fn assemble_section_with_threads(
paras: &[crate::model::paragraph::Paragraph],
per_para: Vec<Vec<Block>>,
thread_counter: &mut usize,
location: &str,
loss: &mut LossReport,
) -> Vec<Block> {
debug_assert_eq!(paras.len(), per_para.len());
let has_columns = paras.iter().any(|p| is_column_chunk_break(p.column_type));
if !has_columns {
let flat: Vec<Block> = per_para.into_iter().flatten().collect();
return group_section_lists(flat);
}
let thread_id = format!("col-{}", *thread_counter);
*thread_counter += 1;
let column_count = section_column_count(paras);
loss.push(LossEntry {
kind: LossKind::SectionSettings,
location: location.to_string(),
detail: match column_count {
Some(n) => format!(
"multi-column layout ({} columns) flattened into one <thread id=\"{}\">; column count/gap not representable in DocLang",
n, thread_id
),
None => format!(
"multi-column layout flattened into one <thread id=\"{}\">; column count/gap not representable in DocLang",
thread_id
),
},
});
let mut flat: Vec<Block> = Vec::new();
let mut emitted_start = false;
let mut pending_head: Option<Block> = None;
for (para, blocks) in paras.iter().zip(per_para) {
if is_column_chunk_break(para.column_type) {
pending_head = Some(if emitted_start {
Block::ThreadContinuation {
thread_id: thread_id.clone(),
}
} else {
Block::ThreadStart {
thread_id: thread_id.clone(),
}
});
emitted_start = true;
}
for block in blocks {
if !emitted_start && pending_head.is_none() {
pending_head = Some(Block::ThreadStart {
thread_id: thread_id.clone(),
});
emitted_start = true;
}
if let Some(head) = pending_head.take() {
flat.push(head);
}
flat.push(block);
}
}
group_section_lists(flat)
}
fn section_column_count(paras: &[crate::model::paragraph::Paragraph]) -> Option<u16> {
let mut max: Option<u16> = None;
for para in paras {
for ctrl in ¶.controls {
if let crate::model::control::Control::ColumnDef(c) = ctrl {
max = Some(max.map_or(c.column_count, |m| m.max(c.column_count)));
}
}
}
max
}
fn group_lists(blocks: Vec<Block>) -> Vec<Block> {
let mut out: Vec<Block> = Vec::with_capacity(blocks.len());
for block in blocks {
match block {
Block::List {
ordered,
mut items,
lost,
prov,
} => {
if let Some(Block::List {
ordered: prev_ordered,
items: prev_items,
..
}) = out.last_mut()
{
if *prev_ordered == ordered {
prev_items.append(&mut items);
continue;
}
}
out.push(Block::List {
ordered,
items,
lost,
prov,
});
}
other => out.push(other),
}
}
out
}
fn bump_footnote_counter(blocks: &[Block], counter: &mut usize) {
for b in blocks {
if let Block::Footnote { .. } = b {
*counter += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::doclang::ir::Inline;
use crate::model::document::{DocInfo, Document};
use crate::model::paragraph::{ColumnBreakType, Paragraph};
use crate::model::style::{HeadType, ParaShape};
fn para(text: &str, para_shape_id: u16) -> Paragraph {
let mut char_offsets = Vec::new();
let mut off: u32 = 0;
for c in text.chars() {
char_offsets.push(off);
off += if (c as u32) > 0xFFFF { 2 } else { 1 };
}
Paragraph {
text: text.to_string(),
char_offsets,
para_shape_id,
..Default::default()
}
}
fn doc_info(shapes: &[(HeadType, u8)]) -> DocInfo {
DocInfo {
para_shapes: shapes
.iter()
.map(|&(head_type, para_level)| ParaShape {
head_type,
para_level,
..Default::default()
})
.collect(),
..Default::default()
}
}
#[test]
fn plain_paragraph() {
let di = doc_info(&[(HeadType::None, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let mut fc = 1;
let out = convert_paragraph(
¶("hello", 0),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p0",
&mut loss,
);
assert_eq!(
out,
vec![Block::Paragraph {
content: vec![Inline::Text("hello".to_string())],
lost: None,
prov: None,
}]
);
}
#[test]
fn outline_becomes_heading_level_plus_one() {
let di = doc_info(&[(HeadType::Outline, 0), (HeadType::Outline, 2)]);
let doc = Document::default();
let mut loss = LossReport::new();
let mut fc = 1;
let h1 = convert_paragraph(
¶("Title", 0),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p0",
&mut loss,
);
let h3 = convert_paragraph(
¶("Sub", 1),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p1",
&mut loss,
);
assert!(matches!(h1[0], Block::Heading { level: 1, .. }));
assert!(matches!(h3[0], Block::Heading { level: 3, .. }));
}
#[test]
fn outline_level_clamped_to_six() {
let di = doc_info(&[(HeadType::Outline, 6)]);
let doc = Document::default();
let mut loss = LossReport::new();
let mut fc = 1;
let out = convert_paragraph(
¶("Deep", 0),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p0",
&mut loss,
);
assert!(matches!(out[0], Block::Heading { level: 6, .. }));
}
#[test]
fn number_and_bullet_become_single_item_lists() {
let di = doc_info(&[(HeadType::Number, 0), (HeadType::Bullet, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let mut fc = 1;
let n = convert_paragraph(
¶("one", 0),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p0",
&mut loss,
);
let b = convert_paragraph(
¶("dot", 1),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p1",
&mut loss,
);
match &n[0] {
Block::List { ordered, items, .. } => {
assert!(*ordered);
assert_eq!(items.len(), 1);
}
other => panic!("expected ordered list, got {other:?}"),
}
match &b[0] {
Block::List { ordered, items, .. } => {
assert!(!*ordered);
assert_eq!(items.len(), 1);
}
other => panic!("expected bullet list, got {other:?}"),
}
}
#[test]
fn page_break_paragraph_prefixes_page_break() {
let di = doc_info(&[(HeadType::None, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let mut fc = 1;
let mut p = para("after break", 0);
p.column_type = ColumnBreakType::Page;
let out = convert_paragraph(&p, &doc, &di, Mode::Lean, &mut fc, "s0/p0", &mut loss);
assert_eq!(out[0], Block::PageBreak);
assert!(matches!(out[1], Block::Paragraph { .. }));
}
#[test]
fn consecutive_bullets_grouped_into_one_list() {
let di = doc_info(&[(HeadType::Bullet, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let paras = vec![para("a", 0), para("b", 0), para("c", 0)];
let out = convert_paragraphs(¶s, &doc, &di, Mode::Lean, "s0", &mut loss);
assert_eq!(out.len(), 1);
match &out[0] {
Block::List { ordered, items, .. } => {
assert!(!*ordered);
assert_eq!(items.len(), 3, "three bullets coalesce into one list");
}
other => panic!("expected one grouped list, got {other:?}"),
}
}
#[test]
fn mixed_ordered_and_bullet_runs_stay_separate() {
let di = doc_info(&[(HeadType::Number, 0), (HeadType::Bullet, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let paras = vec![para("1", 0), para("2", 0), para("dot", 1)];
let out = convert_paragraphs(¶s, &doc, &di, Mode::Lean, "s0", &mut loss);
assert_eq!(out.len(), 2);
match &out[0] {
Block::List {
ordered: true,
items,
..
} => assert_eq!(items.len(), 2),
other => panic!("expected ordered list of 2, got {other:?}"),
}
match &out[1] {
Block::List {
ordered: false,
items,
..
} => assert_eq!(items.len(), 1),
other => panic!("expected bullet list of 1, got {other:?}"),
}
}
#[test]
fn paragraph_between_lists_splits_runs() {
let di = doc_info(&[(HeadType::Bullet, 0), (HeadType::None, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let paras = vec![para("a", 0), para("text", 1), para("b", 0)];
let out = convert_paragraphs(¶s, &doc, &di, Mode::Lean, "s0", &mut loss);
assert_eq!(out.len(), 3);
assert!(matches!(out[0], Block::List { ordered: false, .. }));
assert!(matches!(out[1], Block::Paragraph { .. }));
assert!(matches!(out[2], Block::List { ordered: false, .. }));
}
fn assemble(
paras: &[Paragraph],
di: &DocInfo,
thread_counter: &mut usize,
loss: &mut LossReport,
) -> Vec<Block> {
let doc = Document::default();
let mut per_para: Vec<Vec<Block>> = Vec::new();
let mut fc = 1usize;
for (i, p) in paras.iter().enumerate() {
let loc = format!("s0/p{}", i);
per_para.push(convert_paragraph(
p,
&doc,
di,
Mode::Lean,
&mut fc,
&loc,
loss,
));
}
assemble_section_with_threads(paras, per_para, thread_counter, "s0", loss)
}
#[test]
fn single_column_section_emits_no_thread() {
let di = doc_info(&[(HeadType::None, 0)]);
let mut tc = 0usize;
let mut loss = LossReport::new();
let paras = vec![para("a", 0), para("b", 0)];
let out = assemble(¶s, &di, &mut tc, &mut loss);
assert!(
!out.iter().any(|b| matches!(
b,
Block::ThreadStart { .. } | Block::ThreadContinuation { .. }
)),
"single-column section must not gain a <thread> marker"
);
assert_eq!(tc, 0, "no thread id consumed");
assert!(loss.is_empty(), "no SectionSettings loss for single-column");
}
#[test]
fn column_break_threads_section_into_start_and_continuation() {
let di = doc_info(&[(HeadType::None, 0)]);
let mut tc = 0usize;
let mut loss = LossReport::new();
let mut p_break = para("c", 0);
p_break.column_type = ColumnBreakType::Column;
let paras = vec![para("a", 0), para("b", 0), p_break];
let out = assemble(¶s, &di, &mut tc, &mut loss);
assert!(matches!(out[0], Block::ThreadStart { ref thread_id } if thread_id == "col-0"));
let cont_idx = out
.iter()
.position(|b| matches!(b, Block::ThreadContinuation { .. }))
.expect("a continuation marker");
match &out[cont_idx] {
Block::ThreadContinuation { thread_id } => assert_eq!(thread_id, "col-0"),
_ => unreachable!(),
}
let starts = out
.iter()
.filter(|b| matches!(b, Block::ThreadStart { .. }))
.count();
let conts = out
.iter()
.filter(|b| matches!(b, Block::ThreadContinuation { .. }))
.count();
assert_eq!((starts, conts), (1, 1));
assert_eq!(tc, 1, "one thread id consumed");
}
#[test]
fn multicolumn_break_also_threads() {
let di = doc_info(&[(HeadType::None, 0)]);
let mut tc = 0usize;
let mut loss = LossReport::new();
let mut p_break = para("second", 0);
p_break.column_type = ColumnBreakType::MultiColumn;
let paras = vec![para("first", 0), p_break];
let out = assemble(¶s, &di, &mut tc, &mut loss);
assert!(matches!(out[0], Block::ThreadStart { .. }));
assert!(out
.iter()
.any(|b| matches!(b, Block::ThreadContinuation { .. })));
}
#[test]
fn column_section_records_section_settings_loss_with_count() {
let di = doc_info(&[(HeadType::None, 0)]);
let mut tc = 0usize;
let mut loss = LossReport::new();
let mut p0 = para("a", 0);
p0.controls.push(crate::model::control::Control::ColumnDef(
crate::model::page::ColumnDef {
column_count: 2,
..Default::default()
},
));
let mut p1 = para("b", 0);
p1.column_type = ColumnBreakType::Column;
let paras = vec![p0, p1];
let _ = assemble(¶s, &di, &mut tc, &mut loss);
let entry = loss
.iter()
.find(|e| e.kind == LossKind::SectionSettings)
.expect("a SectionSettings loss for the multi-column layout");
assert!(
entry.detail.contains("2 columns"),
"detail names the column count: {}",
entry.detail
);
}
#[test]
fn section_break_alone_does_not_thread() {
let di = doc_info(&[(HeadType::None, 0)]);
let mut tc = 0usize;
let mut loss = LossReport::new();
let mut p0 = para("a", 0);
p0.column_type = ColumnBreakType::Section;
let paras = vec![p0, para("b", 0)];
let out = assemble(¶s, &di, &mut tc, &mut loss);
assert!(!out.iter().any(|b| matches!(
b,
Block::ThreadStart { .. } | Block::ThreadContinuation { .. }
)));
assert_eq!(tc, 0);
}
#[test]
fn thread_ids_are_unique_across_sections() {
let di = doc_info(&[(HeadType::None, 0)]);
let mut tc = 0usize;
let mut loss = LossReport::new();
let mut b1 = para("b", 0);
b1.column_type = ColumnBreakType::Column;
let out0 = assemble(&[para("a", 0), b1], &di, &mut tc, &mut loss);
let mut d1 = para("d", 0);
d1.column_type = ColumnBreakType::Column;
let out1 = assemble(&[para("c", 0), d1], &di, &mut tc, &mut loss);
let id0 = match &out0[0] {
Block::ThreadStart { thread_id } => thread_id.clone(),
_ => panic!(),
};
let id1 = match &out1[0] {
Block::ThreadStart { thread_id } => thread_id.clone(),
_ => panic!(),
};
assert_eq!(id0, "col-0");
assert_eq!(id1, "col-1");
assert_ne!(id0, id1);
}
#[test]
fn empty_paragraph_emits_no_block() {
let di = doc_info(&[(HeadType::None, 0)]);
let doc = Document::default();
let mut loss = LossReport::new();
let mut fc = 1;
let out = convert_paragraph(
¶("", 0),
&doc,
&di,
Mode::Lean,
&mut fc,
"s0/p0",
&mut loss,
);
assert!(out.is_empty());
}
}