use crate::model::control::Control;
use crate::model::document::{Document, Section};
use crate::model::identity::{used_instance_ids, Allocator};
use crate::model::page::PageDef;
use crate::model::paragraph::{CharShapeRef, LineSeg, Paragraph};
use crate::model::shape::{common_obj_offsets, CommonObjAttr};
use crate::model::table::{Cell, Table, TablePageBreak, VerticalAlign};
use crate::model::Padding;
use crate::scaffold::schema::{
Block, CellAlignSpec, OutlineLevel, PageSize, ScaffoldSpec, OUTLINE_DEFAULTS,
};
const CS_NORMAL: u32 = 0;
const CS_TITLE: u32 = 1;
const CS_HEADING: u32 = 2;
const PS_NORMAL: u16 = 0;
const PS_TITLE: u16 = 1;
const PS_HEADING_BASE: u16 = 2;
const BF_NONE: u16 = 1; const BF_SOLID: u16 = 2;
const OUTLINE_HEAD_ATTR: u32 = (1 << 2) | (1 << 3);
const OUTLINE_TEXT_OFFSET: i16 = 50;
pub fn build_scaffold(spec: &ScaffoldSpec) -> Document {
let mut doc = Document::default();
init_doc_info(&mut doc, &spec.font);
let mut section = Section::default();
section.section_def.page_def = page_def_from_spec(spec.page_size);
section.section_def.page_border_fill.border_fill_id = 1;
section.section_def.page_border_fill.spacing_left = 1417;
section.section_def.page_border_fill.spacing_right = 1417;
section.section_def.page_border_fill.spacing_top = 1417;
section.section_def.page_border_fill.spacing_bottom = 1417;
if let Some(levels) = &spec.outline_numbering {
doc.doc_info.numberings = vec![outline_numbering(levels)];
section.section_def.outline_numbering_id = 1;
}
doc.sections.push(section);
let content_width = content_width_of(&doc.sections[0].section_def.page_def);
let mut ids = Allocator {
used: used_instance_ids(&doc),
next: 1,
};
if let Some(title) = spec
.title
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
doc.sections[0]
.paragraphs
.push(make_text_para(title, PS_TITLE, CS_TITLE));
}
for block in &spec.blocks {
match block {
Block::Heading { level, text } => {
let level = (*level).clamp(1, 7);
let ps_id = PS_HEADING_BASE + (level as u16 - 1);
doc.sections[0]
.paragraphs
.push(make_text_para(text, ps_id, CS_HEADING));
}
Block::Paragraph { text } => {
doc.sections[0]
.paragraphs
.push(make_text_para(text, PS_NORMAL, CS_NORMAL));
}
Block::Table { rows, cell_align } => {
let instance_id = ids.id().unwrap_or(0);
let col_count = rows.iter().map(|r| r.len()).max().unwrap_or(0).max(1);
let cell_para_shape_ids: Vec<u16> = (0..col_count)
.map(|col| match cell_align {
None => PS_NORMAL,
Some(spec) => doc.find_or_create_para_shape(
PS_NORMAL,
&crate::model::style::ParaShapeMods {
alignment: Some(spec.for_column(col).to_alignment()),
..Default::default()
},
),
})
.collect();
if let Some(table_para) =
build_table_paragraph(rows, content_width, instance_id, &cell_para_shape_ids)
{
doc.sections[0].paragraphs.push(table_para);
doc.sections[0].paragraphs.push(Paragraph::new_empty());
}
}
}
}
if doc.sections[0].paragraphs.is_empty() {
doc.sections[0].paragraphs.push(Paragraph::new_empty());
}
doc
}
fn init_doc_info(doc: &mut Document, font_name: &str) {
use crate::model::style::{
Alignment, BorderFill, BorderLine, BorderLineType, CharShape, Font, HeadType, ParaShape,
Style, TabDef,
};
let font_name = if font_name.trim().is_empty() {
"함초롬바탕"
} else {
font_name.trim()
};
let font = Font {
name: font_name.to_string(),
alt_type: 1,
..Default::default()
};
doc.doc_info.font_faces = vec![vec![font]; 7];
let no_border = BorderFill {
borders: [BorderLine {
line_type: BorderLineType::None,
width: 0,
color: 0,
}; 4],
..Default::default()
};
let solid = BorderFill {
borders: [BorderLine {
line_type: BorderLineType::Solid,
width: 1,
color: 0,
}; 4],
..Default::default()
};
doc.doc_info.border_fills = vec![no_border, solid];
doc.doc_info.tab_defs = vec![TabDef::default()];
let base_char_shape = || {
let mut cs = CharShape::default();
cs.ratios = [100; 7];
cs.base_size = 1000; cs.border_fill_id = BF_NONE; cs.text_color = 0x000000;
cs
};
let normal_cs = base_char_shape();
let mut title_cs = base_char_shape();
title_cs.base_size = 1800; title_cs.bold = true;
let mut heading_cs = base_char_shape();
heading_cs.base_size = 1200; heading_cs.bold = true;
doc.doc_info.char_shapes = vec![normal_cs, title_cs, heading_cs];
let normal_ps = ParaShape {
attr1: (1 << 7) | (1 << 8),
line_spacing: 160,
border_fill_id: BF_NONE,
tab_def_id: 0,
..Default::default()
};
let title_ps = ParaShape {
alignment: Alignment::Center,
spacing_before: 300,
spacing_after: 300,
..normal_ps.clone()
};
doc.doc_info.para_shapes = vec![normal_ps.clone(), title_ps];
for level in 1u8..=7 {
doc.doc_info.para_shapes.push(ParaShape {
head_type: HeadType::Outline,
para_level: level - 1,
spacing_before: 200,
spacing_after: 100,
..normal_ps.clone()
});
}
doc.doc_info.styles = vec![Style {
local_name: "바탕글".to_string(),
english_name: "Normal".to_string(),
style_type: 0,
next_style_id: 0,
lang_id: 1042,
para_shape_id: 0,
char_shape_id: 0,
..Default::default()
}];
}
fn outline_numbering(levels: &[OutlineLevel]) -> crate::model::style::Numbering {
use crate::model::style::{Numbering, NumberingHead};
let mut n = Numbering {
start_number: 1,
level_start_numbers: [1; crate::model::style::NUMBERING_LEVELS],
..Default::default()
};
for (i, (default_text, default_format)) in OUTLINE_DEFAULTS.iter().enumerate() {
let (text, format) = match levels.get(i) {
Some(lv) => (lv.text.as_str(), lv.num_format),
None => (*default_text, *default_format),
};
let code = format.code();
n.level_formats[i] = text.to_string();
n.heads[i] = NumberingHead {
attr: OUTLINE_HEAD_ATTR | (u32::from(code) << 5),
width_adjust: 0,
text_distance: OUTLINE_TEXT_OFFSET,
char_shape_id: u32::MAX,
number_format: code,
};
}
n
}
fn page_def_from_spec(page_size: PageSize) -> PageDef {
let mut page_def = PageDef::a4_default();
if (page_size.width_mm - 210.0).abs() > f32::EPSILON
|| (page_size.height_mm - 297.0).abs() > f32::EPSILON
{
page_def.width = mm_to_hwpunit(page_size.width_mm);
page_def.height = mm_to_hwpunit(page_size.height_mm);
}
page_def
}
fn mm_to_hwpunit(mm: f32) -> u32 {
((mm.max(0.0) as f64) * 7200.0 / 25.4).round() as u32
}
fn content_width_of(pd: &PageDef) -> u32 {
let outer_margin_lr: i32 = 283 * 2;
(pd.width as i32 - pd.margin_left as i32 - pd.margin_right as i32 - outer_margin_lr).max(7200)
as u32
}
fn utf16_offsets(text: &str) -> (Vec<u32>, u32) {
let mut offsets = Vec::new();
let mut acc = 0u32;
for c in text.chars() {
offsets.push(acc);
acc += c.len_utf16() as u32;
}
(offsets, acc)
}
const UNCOMPOSED_LINE_SEGS: Vec<LineSeg> = Vec::new();
fn make_text_para(text: &str, para_shape_id: u16, char_shape_id: u32) -> Paragraph {
let (char_offsets, utf16_len) = utf16_offsets(text);
Paragraph {
text: text.to_string(),
char_count: utf16_len + 1, char_offsets,
char_shapes: vec![CharShapeRef {
start_pos: 0,
char_shape_id,
}],
line_segs: UNCOMPOSED_LINE_SEGS,
para_shape_id,
style_id: 0,
has_para_text: true,
..Default::default()
}
}
fn make_cell_para(text: &str, para_shape_id: u16) -> Paragraph {
let (char_offsets, utf16_len) = utf16_offsets(text);
let mut raw_header_extra = vec![0u8; 10];
raw_header_extra[0..2].copy_from_slice(&1u16.to_le_bytes());
Paragraph {
text: text.to_string(),
char_count: utf16_len + 1,
char_count_msb: true, char_offsets,
char_shapes: vec![CharShapeRef {
start_pos: 0,
char_shape_id: CS_NORMAL,
}],
line_segs: UNCOMPOSED_LINE_SEGS,
para_shape_id,
style_id: 0,
has_para_text: !text.is_empty(),
raw_header_extra,
..Default::default()
}
}
fn build_table_paragraph(
rows: &[Vec<String>],
content_width: u32,
instance_id: u32,
cell_para_shape_ids: &[u16],
) -> Option<Paragraph> {
let row_count = rows.len();
if row_count == 0 {
return None;
}
let col_count = rows.iter().map(|r| r.len()).max().unwrap_or(0).max(1);
let row_count_u16 = row_count.min(u16::MAX as usize) as u16;
let col_count_u16 = col_count.min(u16::MAX as usize) as u16;
let cell_pad = Padding {
left: 510,
right: 510,
top: 141,
bottom: 141,
};
let col_width = (content_width / col_count as u32).max(1);
let rendered_row_height: u32 = cell_pad.top as u32 + 1000 + cell_pad.bottom as u32;
let cell_height: u32 = rendered_row_height;
let total_width = col_width * col_count as u32;
let total_height = rendered_row_height * row_count as u32;
let mut cells: Vec<Cell> = Vec::with_capacity(row_count * col_count);
for r in 0..row_count_u16 {
for c in 0..col_count_u16 {
let text = rows
.get(r as usize)
.and_then(|row| row.get(c as usize))
.map(String::as_str)
.unwrap_or("");
let mut cell = Cell::new_empty(c, r, col_width, cell_height, BF_SOLID);
cell.padding = cell_pad;
cell.vertical_align = VerticalAlign::Center;
let para_shape_id = cell_para_shape_ids
.get(c as usize)
.copied()
.unwrap_or(PS_NORMAL);
cell.paragraphs = vec![make_cell_para(text, para_shape_id)];
cell.raw_list_extra = Vec::new();
cells.push(cell);
}
}
let row_sizes: Vec<i16> = (0..row_count_u16).map(|_| col_count_u16 as i16).collect();
let flags: u32 = (2 << 3) | (3 << 8) | (1 << 13) | (4 << 15) | (2 << 18) | (1 << 21);
let outer_margin: i16 = 283; let mut raw_ctrl_data = vec![0u8; 38];
raw_ctrl_data[common_obj_offsets::FLAGS].copy_from_slice(&flags.to_le_bytes());
raw_ctrl_data[common_obj_offsets::WIDTH].copy_from_slice(&total_width.to_le_bytes());
raw_ctrl_data[common_obj_offsets::HEIGHT].copy_from_slice(&total_height.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_LEFT].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_RIGHT].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_TOP].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_BOTTOM].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::INSTANCE_ID].copy_from_slice(&instance_id.to_le_bytes());
let mut table = Table {
attr: 0x082A_2210,
row_count: row_count_u16,
col_count: col_count_u16,
cell_spacing: 0,
padding: cell_pad,
row_sizes,
border_fill_id: BF_SOLID,
zones: Vec::new(),
cells,
cell_grid: Vec::new(),
page_break: TablePageBreak::RowBreak,
repeat_header: true,
caption: None,
common: CommonObjAttr {
treat_as_char: false,
text_wrap: crate::model::shape::TextWrap::TopAndBottom,
vert_rel_to: crate::model::shape::VertRelTo::Para,
horz_rel_to: crate::model::shape::HorzRelTo::Para,
vert_align: crate::model::shape::VertAlign::Top,
horz_align: crate::model::shape::HorzAlign::Left,
flow_with_text: true,
width: total_width,
height: total_height,
instance_id,
..Default::default()
},
outer_margin_left: outer_margin,
outer_margin_right: outer_margin,
outer_margin_top: outer_margin,
outer_margin_bottom: outer_margin,
raw_ctrl_data,
raw_ctrl_seal: None,
raw_table_record_attr: 0x0000_0006, raw_table_record_extra: Vec::new(),
layout_page_break_cache: Default::default(),
};
table.rebuild_grid();
let mut table_raw_header_extra = vec![0u8; 10];
table_raw_header_extra[0..2].copy_from_slice(&1u16.to_le_bytes());
table_raw_header_extra[4..6].copy_from_slice(&1u16.to_le_bytes());
Some(Paragraph {
text: String::new(),
char_count: 9, control_mask: 0x0000_0800,
char_offsets: vec![],
char_shapes: vec![CharShapeRef {
start_pos: 0,
char_shape_id: CS_NORMAL,
}],
line_segs: vec![LineSeg {
text_start: 0,
line_height: 1000,
text_height: 1000,
baseline_distance: 850,
line_spacing: 600,
segment_width: 0, tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..Default::default()
}],
para_shape_id: PS_NORMAL,
style_id: 0,
controls: vec![Control::Table(Box::new(table))],
ctrl_data_records: vec![None],
has_para_text: true,
raw_header_extra: table_raw_header_extra,
char_count_msb: false,
..Default::default()
})
}