use crate::model::control::{Control, FieldType};
use crate::model::header_footer::HeaderFooterApply;
use crate::model::paragraph::Paragraph;
use crate::model::shape::{CommonObjAttr, ShapeObject};
use crate::model::table::Table;
use crate::doclang::ir::{self, Block, Formula};
use crate::doclang::loss::report::{LossEntry, LossKind, LossReport};
use crate::doclang::options::Mode;
use super::geometry;
pub(crate) struct ControlCtx<'a> {
pub mode: Mode,
pub location: &'a str,
pub convert_paragraphs: &'a dyn Fn(&[Paragraph]) -> Vec<Block>,
pub convert_table: &'a dyn Fn(&Table) -> ir::Table,
pub resolve_picture: &'a dyn Fn(u16) -> Option<(Vec<u8>, String)>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ControlOutcome {
Blocks(Vec<Block>),
SectionMarker,
ColumnMarker { count: u16 },
}
impl ControlOutcome {
fn one(block: Block) -> Self {
ControlOutcome::Blocks(vec![block])
}
fn empty() -> Self {
ControlOutcome::Blocks(Vec::new())
}
}
pub(crate) fn convert_control(
ctrl: &Control,
ctx: &ControlCtx<'_>,
footnote_number: usize,
loss: &mut LossReport,
) -> ControlOutcome {
match ctrl {
Control::Table(t) => ControlOutcome::one(Block::Table((ctx.convert_table)(t.as_ref()))),
Control::Picture(p) => {
convert_picture(p.as_ref().image_attr.bin_data_id, &p.common, ctx, loss)
}
Control::Equation(e) => ControlOutcome::one(Block::Formula(Formula {
raw_eqedit: e.script.clone(),
latex: None,
prov: None,
})),
Control::Footnote(f) => ControlOutcome::one(Block::Footnote {
number: footnote_number,
content: (ctx.convert_paragraphs)(&f.paragraphs),
prov: None,
}),
Control::Endnote(e) => {
loss.push(LossEntry {
kind: LossKind::Other("endnote".to_string()),
location: ctx.location.to_string(),
detail: "endnote mapped to footnote (no DocLang endnote element)".to_string(),
});
ControlOutcome::one(Block::Footnote {
number: footnote_number,
content: (ctx.convert_paragraphs)(&e.paragraphs),
prov: None,
})
}
Control::Header(h) => ControlOutcome::one(Block::PageHeader {
content: (ctx.convert_paragraphs)(&h.paragraphs),
apply: map_apply(h.apply_to),
prov: None,
}),
Control::Footer(f) => ControlOutcome::one(Block::PageFooter {
content: (ctx.convert_paragraphs)(&f.paragraphs),
apply: map_apply(f.apply_to),
prov: None,
}),
Control::Shape(s) => convert_shape(s.as_ref(), ctx, loss),
Control::SectionDef(_) => ControlOutcome::SectionMarker,
Control::ColumnDef(c) => ControlOutcome::ColumnMarker {
count: c.column_count,
},
Control::HiddenComment(h) => {
loss.push(LossEntry {
kind: LossKind::Other("hidden comment".to_string()),
location: ctx.location.to_string(),
detail: "hidden comment text rescued as plain blocks".to_string(),
});
ControlOutcome::Blocks((ctx.convert_paragraphs)(&h.paragraphs))
}
Control::Hyperlink(h) => {
loss.push(LossEntry {
kind: LossKind::Other("hyperlink".to_string()),
location: ctx.location.to_string(),
detail: format!(
"hyperlink url={:?} text={:?} (anchor text rescued, link semantics dropped)",
h.url, h.text
),
});
ControlOutcome::Blocks(rescue_text_block(&h.text))
}
Control::Bookmark(b) => {
loss.push(LossEntry {
kind: LossKind::Other("bookmark".to_string()),
location: ctx.location.to_string(),
detail: format!("bookmark: {}", b.name),
});
ControlOutcome::empty()
}
Control::IndexMark(im) => {
loss.push(LossEntry {
kind: LossKind::Other("indexmark".to_string()),
location: ctx.location.to_string(),
detail: if im.second_key.is_empty() {
format!("indexmark: {}", im.first_key)
} else {
format!("indexmark: {} / {}", im.first_key, im.second_key)
},
});
ControlOutcome::empty()
}
Control::Ruby(r) => {
loss.push(LossEntry {
kind: LossKind::Other("ruby".to_string()),
location: ctx.location.to_string(),
detail: format!("ruby (덧말): {} (annotation text rescued)", r.ruby_text),
});
ControlOutcome::Blocks(rescue_text_block(&r.ruby_text))
}
Control::CharOverlap(c) => {
let overlapped: String = c.chars.iter().collect();
loss.push(LossEntry {
kind: LossKind::Other("char overlap".to_string()),
location: ctx.location.to_string(),
detail: format!("char overlap (글자겹침): {} (text rescued)", overlapped),
});
ControlOutcome::Blocks(rescue_text_block(&overlapped))
}
Control::Field(f) => {
if f.field_type != FieldType::Hyperlink {
loss.push(LossEntry {
kind: LossKind::Other("field".to_string()),
location: ctx.location.to_string(),
detail: format!("field type={} command={:?}", f.field_type_str(), f.command),
});
}
ControlOutcome::empty()
}
Control::Form(f) => {
loss.push(LossEntry {
kind: LossKind::Other("form".to_string()),
location: ctx.location.to_string(),
detail: format!("form object name={:?}", f.name),
});
ControlOutcome::empty()
}
Control::Unknown(u) => {
loss.push(LossEntry {
kind: LossKind::Other("unknown control".to_string()),
location: ctx.location.to_string(),
detail: format!("unknown control ctrl_id=0x{:08x}", u.ctrl_id),
});
ControlOutcome::empty()
}
Control::AutoNumber(_)
| Control::NewNumber(_)
| Control::PageNumberPos(_)
| Control::PageNumCtrl(_)
| Control::PageHide(_) => ControlOutcome::empty(),
}
}
fn convert_picture(
bin_data_id: u16,
common: &CommonObjAttr,
ctx: &ControlCtx<'_>,
loss: &mut LossReport,
) -> ControlOutcome {
match (ctx.resolve_picture)(bin_data_id) {
Some((data, extension)) => ControlOutcome::one(Block::Picture {
data,
extension,
geometry: Some(geometry::from_common_attr(common)),
lost: None,
prov: None,
}),
None => {
loss.push(LossEntry {
kind: LossKind::FloatingObject,
location: ctx.location.to_string(),
detail: format!("picture skipped: bin-data id {} not found", bin_data_id),
});
ControlOutcome::empty()
}
}
}
fn convert_shape(
shape: &ShapeObject,
ctx: &ControlCtx<'_>,
loss: &mut LossReport,
) -> ControlOutcome {
let rescued = rescue_shape_paragraphs(shape);
let has_text = !rescued.is_empty();
loss.push(LossEntry {
kind: if has_text {
LossKind::TextBox
} else {
LossKind::FloatingObject
},
location: ctx.location.to_string(),
detail: format!(
"{} ({})",
shape.shape_name(),
if has_text { "text rescued" } else { "no text" },
),
});
let mut blocks = (ctx.convert_paragraphs)(&rescued);
if ctx.mode == Mode::Preserve {
let geo = geometry::from_common_attr(shape.common());
let payload = format!(
"shape={};width={};height={};h_offset={};v_offset={};treat_as_char={}",
shape.shape_name(),
geo.width,
geo.height,
geo.h_offset,
geo.v_offset,
geo.treat_as_char,
);
blocks.push(Block::Custom {
namespace: "hwp:geometry".to_string(),
payload,
});
}
ControlOutcome::Blocks(blocks)
}
fn rescue_shape_paragraphs(shape: &ShapeObject) -> Vec<Paragraph> {
let mut out = Vec::new();
if let Some(drawing) = shape.drawing() {
if let Some(tb) = &drawing.text_box {
out.extend(tb.paragraphs.iter().cloned());
}
}
if let ShapeObject::Group(g) = shape {
for child in &g.children {
out.extend(rescue_shape_paragraphs(child));
}
}
out
}
fn rescue_text_block(text: &str) -> Vec<Block> {
let trimmed = text.trim();
if trimmed.is_empty() {
Vec::new()
} else {
vec![Block::Paragraph {
content: vec![ir::Inline::Text(trimmed.to_string())],
lost: None,
prov: None,
}]
}
}
fn map_apply(apply: HeaderFooterApply) -> ir::HeaderFooterApply {
match apply {
HeaderFooterApply::Both => ir::HeaderFooterApply::All,
HeaderFooterApply::Even => ir::HeaderFooterApply::Even,
HeaderFooterApply::Odd => ir::HeaderFooterApply::Odd,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::control::{Bookmark, CharOverlap, Equation, Hyperlink, Ruby};
use crate::model::footnote::{Endnote, Footnote};
use crate::model::header_footer::Header;
use crate::model::image::Picture;
use crate::model::paragraph::Paragraph;
use crate::model::shape::{DrawingObjAttr, RectangleShape, TextBox};
fn stub_ctx<'a>(
mode: Mode,
convert_paragraphs: &'a dyn Fn(&[Paragraph]) -> Vec<Block>,
convert_table: &'a dyn Fn(&Table) -> ir::Table,
resolve_picture: &'a dyn Fn(u16) -> Option<(Vec<u8>, String)>,
) -> ControlCtx<'a> {
ControlCtx {
mode,
location: "test/loc",
convert_paragraphs,
convert_table,
resolve_picture,
}
}
fn no_picture(_id: u16) -> Option<(Vec<u8>, String)> {
None
}
fn count_paragraphs(ps: &[Paragraph]) -> Vec<Block> {
ps.iter()
.map(|_| Block::Paragraph {
content: Vec::new(),
lost: None,
prov: None,
})
.collect()
}
fn dummy_table(_t: &Table) -> ir::Table {
ir::Table {
rows: 1,
cols: 1,
cells: Vec::new(),
caption: None,
prov: None,
}
}
#[test]
fn equation_script_passthrough() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let eq = Equation {
script: "1 over 2".to_string(),
..Default::default()
};
let out = convert_control(&Control::Equation(Box::new(eq)), &ctx, 1, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => match &blocks[0] {
Block::Formula(f) => {
assert_eq!(f.raw_eqedit, "1 over 2");
assert_eq!(f.latex, None);
}
other => panic!("expected Formula, got {other:?}"),
},
other => panic!("expected Blocks, got {other:?}"),
}
assert!(loss.is_empty());
}
#[test]
fn picture_happy_path() {
let cp = count_paragraphs;
let ct = dummy_table;
let resolve = |id: u16| -> Option<(Vec<u8>, String)> {
if id == 7 {
Some((vec![0x89, 0x50], "png".to_string()))
} else {
None
}
};
let ctx = stub_ctx(Mode::Preserve, &cp, &ct, &resolve);
let mut loss = LossReport::new();
let mut pic = Picture::default();
pic.image_attr.bin_data_id = 7;
let out = convert_control(&Control::Picture(Box::new(pic)), &ctx, 1, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => match &blocks[0] {
Block::Picture {
data,
extension,
geometry,
..
} => {
assert_eq!(data, &vec![0x89, 0x50]);
assert_eq!(extension, "png");
assert!(geometry.is_some());
}
other => panic!("expected Picture, got {other:?}"),
},
other => panic!("expected Blocks, got {other:?}"),
}
assert!(loss.is_empty());
}
#[test]
fn picture_missing_bindata_records_loss_and_skips() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let mut pic = Picture::default();
pic.image_attr.bin_data_id = 99; let out = convert_control(&Control::Picture(Box::new(pic)), &ctx, 1, &mut loss);
assert_eq!(out, ControlOutcome::Blocks(Vec::new()));
assert_eq!(loss.len(), 1);
assert_eq!(loss.iter().next().unwrap().kind, LossKind::FloatingObject);
}
#[test]
fn footnote_recurses_via_callback() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let fnote = Footnote {
number: 3,
paragraphs: vec![Paragraph::default(), Paragraph::default()],
..Default::default()
};
let out = convert_control(&Control::Footnote(Box::new(fnote)), &ctx, 5, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => match &blocks[0] {
Block::Footnote {
number, content, ..
} => {
assert_eq!(*number, 5); assert_eq!(content.len(), 2); }
other => panic!("expected Footnote, got {other:?}"),
},
other => panic!("expected Blocks, got {other:?}"),
}
assert!(loss.is_empty());
}
#[test]
fn endnote_records_loss_entry() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let en = Endnote {
number: 1,
paragraphs: vec![Paragraph::default()],
..Default::default()
};
let out = convert_control(&Control::Endnote(Box::new(en)), &ctx, 2, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => {
assert!(matches!(blocks[0], Block::Footnote { .. }));
}
other => panic!("expected Blocks, got {other:?}"),
}
assert_eq!(loss.len(), 1);
assert_eq!(
loss.iter().next().unwrap().kind,
LossKind::Other("endnote".to_string())
);
}
#[test]
fn header_apply_mapping() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let header = Header {
apply_to: HeaderFooterApply::Odd,
paragraphs: vec![Paragraph::default()],
..Default::default()
};
let out = convert_control(&Control::Header(Box::new(header)), &ctx, 1, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => match &blocks[0] {
Block::PageHeader { apply, content, .. } => {
assert_eq!(*apply, ir::HeaderFooterApply::Odd);
assert_eq!(content.len(), 1);
}
other => panic!("expected PageHeader, got {other:?}"),
},
other => panic!("expected Blocks, got {other:?}"),
}
}
#[test]
fn shape_text_rescue() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let rect = RectangleShape {
drawing: DrawingObjAttr {
text_box: Some(TextBox {
paragraphs: vec![Paragraph::default(), Paragraph::default()],
..Default::default()
}),
..Default::default()
},
..Default::default()
};
let shape = ShapeObject::Rectangle(rect);
let out = convert_control(&Control::Shape(Box::new(shape)), &ctx, 1, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => {
assert_eq!(blocks.len(), 2);
}
other => panic!("expected Blocks, got {other:?}"),
}
assert_eq!(loss.len(), 1);
assert_eq!(loss.iter().next().unwrap().kind, LossKind::TextBox);
}
#[test]
fn shape_preserve_appends_custom_geometry() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Preserve, &cp, &ct, &np);
let mut loss = LossReport::new();
let rect = RectangleShape::default(); let shape = ShapeObject::Rectangle(rect);
let out = convert_control(&Control::Shape(Box::new(shape)), &ctx, 1, &mut loss);
match out {
ControlOutcome::Blocks(blocks) => {
assert_eq!(blocks.len(), 1);
match &blocks[0] {
Block::Custom { namespace, .. } => assert_eq!(namespace, "hwp:geometry"),
other => panic!("expected Custom, got {other:?}"),
}
}
other => panic!("expected Blocks, got {other:?}"),
}
assert_eq!(loss.iter().next().unwrap().kind, LossKind::FloatingObject);
}
#[test]
fn column_def_yields_marker() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let cd = crate::model::page::ColumnDef {
column_count: 3,
..Default::default()
};
let out = convert_control(&Control::ColumnDef(cd), &ctx, 1, &mut loss);
assert_eq!(out, ControlOutcome::ColumnMarker { count: 3 });
}
#[test]
fn bookmark_records_loss() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let out = convert_control(
&Control::Bookmark(Bookmark {
name: "ch1".to_string(),
}),
&ctx,
1,
&mut loss,
);
assert_eq!(out, ControlOutcome::empty());
assert_eq!(loss.len(), 1);
}
#[test]
fn hyperlink_rescues_text_and_records_loss() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let out = convert_control(
&Control::Hyperlink(Hyperlink {
url: "https://x".to_string(),
text: "Example".to_string(),
}),
&ctx,
1,
&mut loss,
);
assert_eq!(
out,
ControlOutcome::Blocks(vec![Block::Paragraph {
content: vec![ir::Inline::Text("Example".to_string())],
lost: None,
prov: None,
}])
);
assert_eq!(loss.len(), 1);
}
#[test]
fn hyperlink_empty_text_emits_no_block() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let out = convert_control(
&Control::Hyperlink(Hyperlink {
url: "https://x".to_string(),
text: " ".to_string(),
}),
&ctx,
1,
&mut loss,
);
assert_eq!(out, ControlOutcome::empty());
assert_eq!(loss.len(), 1);
}
#[test]
fn ruby_rescues_annotation_and_records_loss() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let out = convert_control(
&Control::Ruby(Ruby {
ruby_text: "가나다".to_string(),
..Default::default()
}),
&ctx,
1,
&mut loss,
);
assert_eq!(
out,
ControlOutcome::Blocks(vec![Block::Paragraph {
content: vec![ir::Inline::Text("가나다".to_string())],
lost: None,
prov: None,
}])
);
assert_eq!(loss.len(), 1);
}
#[test]
fn char_overlap_rescues_glyphs_and_records_loss() {
let cp = count_paragraphs;
let ct = dummy_table;
let np = no_picture;
let ctx = stub_ctx(Mode::Lean, &cp, &ct, &np);
let mut loss = LossReport::new();
let out = convert_control(
&Control::CharOverlap(CharOverlap {
chars: vec!['企', '業'],
..Default::default()
}),
&ctx,
1,
&mut loss,
);
assert_eq!(
out,
ControlOutcome::Blocks(vec![Block::Paragraph {
content: vec![ir::Inline::Text("企業".to_string())],
lost: None,
prov: None,
}])
);
assert_eq!(loss.len(), 1);
}
}