use super::byte_writer::{char_to_wchar, ByteWriter};
pub use super::char_shape::serialize_char_shape;
use super::record_writer::write_record;
use crate::model::bin_data::{BinData, BinDataType};
use crate::model::document::{DocInfo, DocProperties};
use crate::model::raw_provenance;
use crate::model::style::{
BorderFill, BorderLineType, Bullet, CenterLine, FillType, Font, ImageFillMode, Numbering,
ParaShape, Style, TabDef, NUMBERING_LEVELS,
};
use crate::parser::tags;
use std::borrow::Cow;
enum Payload<'a> {
DocumentProperties(&'a DocProperties),
IdMappings(&'a DocInfo),
BinData(&'a BinData),
FaceName(&'a Font),
BorderFill(&'a BorderFill),
CharShape(&'a crate::model::style::CharShape),
TabDef(&'a TabDef),
Numbering(&'a Numbering),
Bullet(&'a Bullet),
ParaShape(&'a ParaShape),
Style(&'a Style),
}
impl super::byte_writer::BinaryProducer for Payload<'_> {
fn write<W: std::io::Write>(&self, writer: &mut ByteWriter<W>) -> std::io::Result<()> {
match self {
Self::DocumentProperties(value) => {
write_serialize_document_properties_from_model(value, writer)
}
Self::IdMappings(value) => write_serialize_id_mappings(value, writer),
Self::BinData(value) => write_serialize_bin_data(value, writer),
Self::FaceName(value) => write_serialize_face_name(value, writer),
Self::BorderFill(value) => write_serialize_border_fill(value, writer),
Self::CharShape(value) => super::char_shape::write_char_shape(value, writer),
Self::TabDef(value) => write_serialize_tab_def(value, writer),
Self::Numbering(value) => write_serialize_numbering(value, writer),
Self::Bullet(value) => write_serialize_bullet(value, writer),
Self::ParaShape(value) => write_serialize_para_shape(value, writer),
Self::Style(value) => write_serialize_style(value, writer),
}
}
}
pub fn serialize_doc_info(doc_info: &DocInfo, doc_props: &DocProperties) -> Vec<u8> {
match try_serialize_doc_info(doc_info, doc_props, &crate::storage::Unbounded) {
Ok(bytes) => bytes,
Err(never) => match never {},
}
}
pub(crate) fn try_serialize_doc_info<S: crate::storage::Storage>(
doc_info: &DocInfo,
doc_props: &DocProperties,
storage: &S,
) -> Result<Vec<u8>, S::Error> {
if !doc_info.raw_stream_dirty && doc_info.raw_provenance_permits_reuse(doc_props) {
if let Some(ref raw) = doc_info.raw_stream {
let mut result = storage.copy_slice(raw)?;
if doc_info.distribute_doc_data_removed {
surgical_remove_records(&mut result, tags::HWPTAG_DISTRIBUTE_DOC_DATA);
}
return Ok(result);
}
}
let mut stream = Vec::new();
let seals = doc_info.raw_provenance.as_ref().map(|s| &s.record_seals);
let props_data = match (doc_props.raw_data.as_ref(), seals) {
(Some(raw), None) => Cow::Borrowed(raw.as_slice()),
(Some(raw), Some(s)) if s.props == raw_provenance::record_digest(doc_props) => {
Cow::Borrowed(raw.as_slice())
}
_ => Cow::Owned(storage.binary(&Payload::DocumentProperties(doc_props))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_DOCUMENT_PROPERTIES,
0,
&props_data,
storage,
)?;
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_ID_MAPPINGS,
0,
&storage.binary(&Payload::IdMappings(doc_info))?,
storage,
)?;
fn sealed_raw<'a, T: serde::Serialize>(
record: &'a T,
raw: &'a Option<Vec<u8>>,
seals: Option<&[[u8; 32]]>,
idx: usize,
) -> Option<&'a Vec<u8>> {
raw.as_ref()
.filter(|_| raw_provenance::record_raw_permitted(seals, idx, record))
}
for (i, bin_data) in doc_info.bin_data_list.iter().enumerate() {
let data = match sealed_raw(
bin_data,
&bin_data.raw_data,
seals.map(|s| &s.bin_data[..]),
i,
) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::BinData(bin_data))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_BIN_DATA,
1,
&data,
storage,
)?;
}
for (li, lang_fonts) in doc_info.font_faces.iter().enumerate() {
let lang_seals = seals.and_then(|s| s.fonts.get(li)).map(|v| &v[..]);
for (fi, font) in lang_fonts.iter().enumerate() {
let data = match sealed_raw(font, &font.raw_data, lang_seals, fi) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::FaceName(font))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_FACE_NAME,
1,
&data,
storage,
)?;
}
}
for (i, bf) in doc_info.border_fills.iter().enumerate() {
let data = match sealed_raw(bf, &bf.raw_data, seals.map(|s| &s.border_fills[..]), i) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::BorderFill(bf))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_BORDER_FILL,
1,
&data,
storage,
)?;
}
for (i, cs) in doc_info.char_shapes.iter().enumerate() {
let data = match sealed_raw(cs, &cs.raw_data, seals.map(|s| &s.char_shapes[..]), i) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::CharShape(cs))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_CHAR_SHAPE,
1,
&data,
storage,
)?;
}
for (i, td) in doc_info.tab_defs.iter().enumerate() {
let data = match sealed_raw(td, &td.raw_data, seals.map(|s| &s.tab_defs[..]), i) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::TabDef(td))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_TAB_DEF,
1,
&data,
storage,
)?;
}
for (i, numbering) in doc_info.numberings.iter().enumerate() {
let data = match sealed_raw(
numbering,
&numbering.raw_data,
seals.map(|s| &s.numberings[..]),
i,
) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::Numbering(numbering))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_NUMBERING,
1,
&data,
storage,
)?;
}
for (i, bullet) in doc_info.bullets.iter().enumerate() {
let data = match sealed_raw(bullet, &bullet.raw_data, seals.map(|s| &s.bullets[..]), i) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::Bullet(bullet))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_BULLET,
1,
&data,
storage,
)?;
}
for (i, ps) in doc_info.para_shapes.iter().enumerate() {
let data = match sealed_raw(ps, &ps.raw_data, seals.map(|s| &s.para_shapes[..]), i) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::ParaShape(ps))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_PARA_SHAPE,
1,
&data,
storage,
)?;
}
for (i, style) in doc_info.styles.iter().enumerate() {
let data = match sealed_raw(style, &style.raw_data, seals.map(|s| &s.styles[..]), i) {
Some(raw) => Cow::Borrowed(raw.as_slice()),
None => Cow::Owned(storage.binary(&Payload::Style(style))?),
};
super::record_writer::try_append_record(
&mut stream,
tags::HWPTAG_STYLE,
1,
&data,
storage,
)?;
}
for record in &doc_info.extra_records {
super::record_writer::try_append_record(
&mut stream,
record.tag_id,
record.level,
&record.data,
storage,
)?;
}
Ok(stream)
}
pub fn serialize_document_properties(props: &DocProperties) -> Vec<u8> {
if let Some(ref raw) = props.raw_data {
return raw.clone();
}
serialize_document_properties_from_model(props)
}
fn serialize_document_properties_from_model(props: &DocProperties) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_document_properties_from_model(props, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_document_properties_from_model<W: std::io::Write>(
props: &DocProperties,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
w.write_u16(props.section_count)?;
w.write_u16(props.page_start_num)?;
w.write_u16(props.footnote_start_num)?;
w.write_u16(props.endnote_start_num)?;
w.write_u16(props.picture_start_num)?;
w.write_u16(props.table_start_num)?;
w.write_u16(props.equation_start_num)?;
w.write_u32(props.caret_list_id)?;
w.write_u32(props.caret_para_id)?;
w.write_u32(props.caret_char_pos)?;
Ok(())
}
pub fn serialize_id_mappings(doc_info: &DocInfo) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_id_mappings(doc_info, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_id_mappings<W: std::io::Write>(
doc_info: &DocInfo,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
w.write_u32(doc_info.bin_data_list.len() as u32)?;
for lang_idx in 0..7 {
let count = if lang_idx < doc_info.font_faces.len() {
doc_info.font_faces[lang_idx].len() as u32
} else {
0
};
w.write_u32(count)?;
}
w.write_u32(doc_info.border_fills.len() as u32)?;
w.write_u32(doc_info.char_shapes.len() as u32)?;
w.write_u32(doc_info.tab_defs.len() as u32)?;
w.write_u32(doc_info.numberings.len() as u32)?;
let bullet_count = if doc_info.bullets.is_empty() {
doc_info.bullet_count
} else {
doc_info.bullets.len() as u32
};
w.write_u32(bullet_count)?;
w.write_u32(doc_info.para_shapes.len() as u32)?;
w.write_u32(doc_info.styles.len() as u32)?;
w.write_u32(doc_info.memo_shape_count)?;
w.write_u32(0)?;
w.write_u32(0)?;
Ok(())
}
pub fn serialize_bin_data(bin_data: &BinData) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_bin_data(bin_data, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_bin_data<W: std::io::Write>(
bin_data: &BinData,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
w.write_u16(bin_data.attr)?;
match bin_data.data_type {
BinDataType::Link => {
if let Some(ref abs_path) = bin_data.abs_path {
w.write_hwp_string(abs_path)?;
} else {
w.write_hwp_string("")?;
}
if let Some(ref rel_path) = bin_data.rel_path {
w.write_hwp_string(rel_path)?;
} else {
w.write_hwp_string("")?;
}
}
BinDataType::Embedding | BinDataType::Storage => {
w.write_u16(bin_data.storage_id)?;
if let Some(ref ext) = bin_data.extension {
w.write_hwp_string(ext)?;
} else {
w.write_hwp_string("")?;
}
}
}
Ok(())
}
const FONT_DEFAULT_NAMES: &[(&str, &str)] = &[
("#견고딕", "#Gyeongothic"),
("#견명조", "#Gyeonmyeongjo"),
("#그래픽", "#Graphic"),
("#디나루", "#Dinaru"),
("#세고딕", "#Segothic"),
("#세나루", "#Senaru"),
("#세명조", "#Semyeongjo"),
("#신그래픽", "#Singraphic"),
("#신디나루", "#Sindinaru"),
("#신명조", "#Sinmyeongjo"),
("#신문견고", "#Sinmungyeongo"),
("#신문태고", "#Sinmuntaego"),
("#신문태명", "#Sinmuntaemyeong"),
("#신세고딕", "#Sinsegothic"),
("#신중명조", "#Sin Jungmyeongjo"),
("#신태명조", "#Sintaemyeongjo"),
("#중고딕", "#Junggothic"),
("#중명조", "#Jungmyeongjo"),
("#태고딕", "#Taegothic"),
("#태그래픽", "#Taegraphic"),
("#태명조", "#Taemyeongjo"),
("#태신명조", "#Taesinmyeongjo"),
("-윤고딕340", "YDIYGO340"),
("08서울남산체 B", "08SeoulNamsan B"),
("08서울남산체 EB", "08SeoulNamsan EB"),
("08서울남산체 M", "08SeoulNamsan M"),
("08서울한강체 L", "08SeoulHangang L"),
("08서울한강체 M", "08SeoulHangang M"),
("AmeriGarmnd BT", "AmeriGarmnd BT"),
("Arial", "Arial"),
("Arial Black", "Arial Black"),
("Arial Narrow", "Arial Narrow"),
("Arial Unicode MS", "Arial Unicode MS"),
("Calibri", "Calibri"),
("Century", "Century"),
("Courier New", "Courier New"),
("Garamond", "Garamond"),
("HCI Acacia", "HCI Acacia"),
("HCI Bellflower", "HCI Bellflower"),
("HCI Hollyhock", "HCI Hollyhock"),
("HCI Morning Glory", "HCI Morning Glory"),
("HCI Poppy", "HCI Poppy"),
("HCI Tulip", "HCI Tulip"),
("HY강B", "HYkanB"),
("HY강M", "HYkanM"),
("HY견고딕", "HYGothic-Extra"),
("HY견명조", "HYMyeongJo-Extra"),
("HY궁서", "HYgsrB"),
("HY그래픽", "HYgprM"),
("HY그래픽M", "HYGraphic-Medium"),
("HY동녘M", "HYdnkM"),
("HY백송B", "HYbsrB"),
("HY수평선B", "HYsupB"),
("HY수평선M", "HYsupM"),
("HY신명조", "HYSinMyeongJo-Medium"),
("HY엽서M", "HYPost-Medium"),
("HY울릉도B", "HYwulB"),
("HY울릉도M", "HYwulM"),
("HY중고딕", "HYGothic-Medium"),
("HY헤드라인M", "HYHeadLine-Medium"),
("Hobo BT", "Hobo BT"),
("KoPubWorld돋움체 Bold", "KoPubWorldDotum Bold"),
("KoPub돋움체 Bold", "KoPubDotum Bold"),
("KoPub돋움체 Light", "KoPubDotum Light"),
("KoPub돋움체 Medium", "KoPubDotum Medium"),
("KoPub바탕체 Bold", "KoPubBatang Bold"),
("KoPub바탕체 Light", "KoPubBatang Light"),
("KoPub바탕체 Medium", "KoPubBatang Medium"),
("MS PMincho", "MS PMincho"),
("Noto Sans CJK KR Bold", "Noto Sans CJK KR Bold"),
("Noto Sans CJK KR DemiLight", "Noto Sans CJK KR DemiLight"),
("Noto Sans CJK KR Medium", "Noto Sans CJK KR Medium"),
("SimSun", "SimSun"),
("Tahoma", "Tahoma"),
("Times New Roman", "Times New Roman"),
("Trebuchet MS", "Trebuchet MS"),
("Verdana", "Verdana"),
("가는안상수체", "가는안상수체"),
("가는한", "Ganeunhan"),
("경기천년바탕 Regular", "GyeonggiBatang Regular"),
("고딕", "Gothic"),
("굴림", "Gulim"),
("굴림체", "GulimChe"),
("궁서", "Gungsuh"),
("궁서체", "GungsuhChe"),
("나눔고딕", "NanumGothic"),
("나눔고딕 ExtraBold", "NanumGothicExtraBold"),
("나눔명조", "NanumMyeongjo"),
("나눔명조 ExtraBold", "NanumMyeongjoExtraBold"),
("돋움", "Dotum"),
("돋움체", "DotumChe"),
("맑은 고딕", "Malgun Gothic"),
("맑은 고딕 Semilight", "Malgun Gothic Semilight"),
("명조", "Myeongjo"),
("문체부 궁체 정자체", "MGungJeong"),
("문체부 돋음체", "MDotum"),
("문체부 바탕체", "MBatang"),
("문체부 쓰기 흘림체", "MSugiHeulim"),
("문체부 제목 돋음체", "MJemokGothic"),
("바탕", "Batang"),
("바탕체", "BatangChe"),
("산세리프", "Sans Serif"),
("새굴림", "New Gulim"),
("시스템", "System"),
("신명 견고딕", "Sinmyeong Gyeongothic"),
("신명 견명조", "Sinmyeong Gyeonmyeongjo"),
("신명 궁서", "Sinmyeong Gungseo"),
("신명 디나루", "Sinmyeong Dinaru"),
("신명 세나루", "Sinmyeong Senaru"),
("신명 세명조", "Sinmyeong Semyeongjo"),
("신명 순명조", "Sinmyeong Sunmyeongjo"),
("신명 신그래픽", "Sinmyeong Singraphic"),
("신명 신명조", "Sinmyeong Sinmyeongjo"),
("신명 신문명조", "Sinmyeong Sinmunmyeongjo"),
("신명 신신명조", "Sinmyeong Sinsinmyeongjo"),
("신명 중고딕", "Sinmyeong Junggothic"),
("신명 중명조", "Sinmyeong Jungmyeongjo"),
("신명 태고딕", "Sinmyeong Taegothic"),
("신명 태그래픽", "Sinmyeong Taegraphic"),
("신명 태명조", "Sinmyeong Taemyeongjo"),
("신명조 간자", "Sinmyeongjo Chinese"),
("신명조 약자", "Sinmyeongjo Jananese"),
("양재 다운명조M", "YJ Daunmyeongjo M"),
("양재 튼튼B", "YJ Teunteun B"),
("옥수수", "Corn"),
("중고딕 간자", "Junggothic Chinese"),
("태 가는 헤드라인D", "Tae Headline D Narrow"),
("태 가는 헤드라인T", "Tae Headline T Narrow"),
("태 나무", "태 나무"),
("태 헤드라인T", "Tae Headline T"),
("필기", "Pilgi"),
("한양견고딕", "HY Gyeongothic"),
("한양견명조", "HY Gyeonmyeongjo"),
("한양궁서", "HY Gungseo"),
("한양그래픽", "HY Graphic"),
("한양신명조", "HY Sinmyeongjo"),
("한양신명조V", "HY Sinmyeongjo V"),
("한양중고딕", "HY Junggothic"),
("한양중고딕V", "HY Junggothic V"),
("한양해서", "HYhaeseo"),
("한컴 백제 M", "Haan Baekje M"),
("한컴 윤고딕 250", "Haan YGodic 250"),
("한컴 쿨재즈 B", "Haan Cooljazz B"),
("한컴돋움", "Haansoft Dotum"),
("한컴바탕", "Haansoft Batang"),
("한컴산뜻돋움", "Han Santteut Dotum Regular"),
("함초롬돋움", "HCR Dotum"),
("함초롬돋움 확장", "HCR Dotum Ext"),
("함초롬바탕", "HCR Batang"),
("휴먼고딕", "휴먼고딕"),
("휴먼둥근헤드라인", "Headline R"),
("휴먼명조", "휴먼명조"),
("휴먼모음T", "MoeumT R"),
("휴먼아미체", "Ami R"),
("휴먼엑스포", "Expo M"),
("휴먼옛체", "Yet R"),
];
fn measured_default_font_name(name: &str) -> Option<&'static str> {
FONT_DEFAULT_NAMES
.iter()
.find(|(korean, _)| *korean == name)
.map(|(_, default)| *default)
}
pub fn serialize_face_name(font: &Font) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_face_name(font, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_face_name<W: std::io::Write>(
font: &Font,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
let alt_name = font.alt_name.as_deref().or_else(|| {
font.subst_font
.as_ref()
.map(|s| s.face.as_str())
.filter(|face| !face.is_empty())
});
let default_name = font
.default_name
.as_deref()
.or_else(|| measured_default_font_name(&font.name));
let mut attr = font.alt_type & 0x03;
if alt_name.is_some() {
attr |= 0x80;
}
if font.type_info.is_some() {
attr |= 0x40;
}
if default_name.is_some() {
attr |= 0x20;
}
w.write_u8(attr)?;
w.write_hwp_string(&font.name)?;
if let Some(alt_name) = alt_name {
let alt_type = font
.subst_font
.as_ref()
.filter(|substitute| substitute.face == alt_name)
.map_or(font.alt_type & 0x03, |substitute| substitute.font_type);
w.write_u8(alt_type)?;
w.write_hwp_string(alt_name)?;
}
if let Some(type_info) = font.type_info {
w.write_bytes(&type_info)?;
}
if let Some(default_name) = default_name {
w.write_hwp_string(default_name)?;
}
Ok(())
}
fn border_line_type_to_u8(lt: BorderLineType) -> u8 {
match lt {
BorderLineType::None => 0,
BorderLineType::Solid => 1,
BorderLineType::Dash => 2,
BorderLineType::Dot => 3,
BorderLineType::DashDot => 4,
BorderLineType::DashDotDot => 5,
BorderLineType::LongDash => 6,
BorderLineType::Circle => 7,
BorderLineType::Double => 8,
BorderLineType::ThinThickDouble => 9,
BorderLineType::ThickThinDouble => 10,
BorderLineType::ThinThickThinTriple => 11,
BorderLineType::Wave => 12,
BorderLineType::DoubleWave => 13,
BorderLineType::Thick3D => 14,
BorderLineType::Thick3DReverse => 15,
BorderLineType::Thin3D => 16,
BorderLineType::Thin3DReverse => 17,
}
}
pub(super) fn image_fill_mode_to_u8(mode: ImageFillMode) -> u8 {
match mode {
ImageFillMode::TileAll => 0,
ImageFillMode::TileHorzTop => 1,
ImageFillMode::TileHorzBottom => 2,
ImageFillMode::TileVertLeft => 3,
ImageFillMode::TileVertRight => 4,
ImageFillMode::FitToSize | ImageFillMode::Total => 5,
ImageFillMode::Center => 6,
ImageFillMode::CenterTop => 7,
ImageFillMode::CenterBottom => 8,
ImageFillMode::LeftCenter => 9,
ImageFillMode::LeftTop => 10,
ImageFillMode::LeftBottom => 11,
ImageFillMode::RightCenter => 12,
ImageFillMode::RightTop => 13,
ImageFillMode::RightBottom => 14,
ImageFillMode::None | ImageFillMode::Zoom => 15,
}
}
pub fn serialize_border_fill(bf: &BorderFill) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_border_fill(bf, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_border_fill<W: std::io::Write>(
bf: &BorderFill,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
let mut attr = bf.attr;
let center_line = if bf.center_line != CenterLine::None {
bf.center_line
} else {
CenterLine::from_hwp_attr(attr)
};
if center_line != CenterLine::None {
attr &= !((0x07 << 2)
| (0x07 << 5)
| (0x03 << 8)
| (1 << 10)
| (1 << 11)
| (1 << 12)
| (1 << 13));
attr |= center_line.hwp_binary_attr_bits();
}
w.write_u16(attr)?;
for border in &bf.borders {
w.write_u8(border_line_type_to_u8(border.line_type))?;
w.write_u8(border.width)?;
w.write_color_ref(border.color)?;
}
w.write_u8(bf.diagonal.diagonal_type)?;
w.write_u8(bf.diagonal.width)?;
w.write_color_ref(bf.diagonal.color)?;
serialize_fill(w, &bf.fill)?;
Ok(())
}
fn serialize_fill<W: std::io::Write>(
w: &mut ByteWriter<W>,
fill: &crate::model::style::Fill,
) -> std::io::Result<()> {
let fill_type_val: u32 = match fill.fill_type {
FillType::None => 0,
FillType::Solid => 1,
FillType::Image => 2,
FillType::Gradient => 4,
};
w.write_u32(fill_type_val)?;
match fill.fill_type {
FillType::Solid => {
if let Some(ref solid) = fill.solid {
w.write_color_ref(solid.background_color)?;
w.write_color_ref(solid.pattern_color)?;
w.write_i32(solid.pattern_type)?;
}
w.write_u32(0)?;
w.write_u8(fill.alpha)?;
}
FillType::Gradient => {
if let Some(ref grad) = fill.gradient {
w.write_u8(grad.gradient_type as u8)?;
w.write_u32(grad.angle as u32)?;
w.write_u32(grad.center_x as u32)?;
w.write_u32(grad.center_y as u32)?;
w.write_u32(grad.blur as u32)?;
w.write_u32(grad.colors.len() as u32)?;
if grad.colors.len() > 2 {
for &pos in &grad.positions {
w.write_i32(pos)?;
}
}
for &color in &grad.colors {
w.write_color_ref(color)?;
}
}
w.write_u32(1)?;
w.write_u8(fill.gradient.as_ref().map(|g| g.step_center).unwrap_or(0))?;
w.write_u8(fill.alpha)?;
}
FillType::Image => {
if let Some(ref img) = fill.image {
w.write_u8(image_fill_mode_to_u8(img.fill_mode))?;
w.write_i8(img.brightness)?;
w.write_i8(img.contrast)?;
w.write_u8(img.effect)?;
w.write_u16(img.bin_data_id)?;
}
w.write_u32(0)?;
w.write_u8(fill.alpha)?;
}
FillType::None => {
w.write_u32(0)?;
}
}
Ok(())
}
pub fn serialize_tab_def(td: &TabDef) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_tab_def(td, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_tab_def<W: std::io::Write>(
td: &TabDef,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
let attr = (td.attr & !0x03) | (td.auto_tab_left as u32) | ((td.auto_tab_right as u32) << 1);
w.write_u32(attr)?;
w.write_u32(td.tabs.len() as u32)?;
for tab in &td.tabs {
w.write_u32(tab.position)?;
w.write_u8(tab.tab_type)?;
w.write_u8(tab.fill_type)?;
w.write_zeros(2)?; }
Ok(())
}
fn serialize_numbering(numbering: &Numbering) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_numbering(numbering, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_numbering<W: std::io::Write>(
numbering: &Numbering,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
for level in 0..7 {
write_numbering_level(numbering, level, w)?;
}
w.write_u16(numbering.start_number)?;
for level in 0..7 {
w.write_u32(numbering.level_start_numbers[level])?;
}
for level in 7..NUMBERING_LEVELS {
write_numbering_level(numbering, level, w)?;
}
for level in 7..NUMBERING_LEVELS {
w.write_u32(numbering.level_start_numbers[level])?;
}
Ok(())
}
fn write_numbering_level<W: std::io::Write>(
numbering: &Numbering,
level: usize,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
let head = &numbering.heads[level];
let attr = (head.attr & !(0x1f << 5)) | ((head.number_format as u32 & 0x1f) << 5);
w.write_u32(attr)?;
w.write_i16(head.width_adjust)?;
w.write_i16(head.text_distance)?;
w.write_u32(head.char_shape_id)?;
let fmt_str = &numbering.level_formats[level];
w.write_u16(fmt_str.encode_utf16().count() as u16)?;
for ch in fmt_str.encode_utf16() {
w.write_u16(ch)?;
}
Ok(())
}
fn serialize_bullet(bullet: &Bullet) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_bullet(bullet, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_bullet<W: std::io::Write>(
bullet: &Bullet,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
w.write_u32(bullet.attr)?;
w.write_i16(bullet.width_adjust)?;
w.write_i16(bullet.text_distance)?;
w.write_u32(bullet.char_shape_id)?;
w.write_u16(char_to_wchar(bullet.bullet_char))?;
let hwpx_image = bullet
.raw_para_head
.is_some()
.then(|| bullet.image_reference())
.flatten();
w.write_i32(if hwpx_image.is_some() {
1
} else {
bullet.image_bullet
})?;
let mut image_data = bullet.image_data;
if let Some(id) = hwpx_image {
image_data[3] = u8::try_from(id).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"그림 글머리표 BinData 순번이 HWP 범위를 초과합니다",
)
})?;
}
for &byte in &image_data {
w.write_u8(byte)?;
}
w.write_u16(char_to_wchar(bullet.check_bullet_char))?;
Ok(())
}
fn line_spacing_fields(ps: &ParaShape) -> (u32, i32, u32, u32) {
use crate::model::style::LineSpacingType;
let value = ps.line_spacing.max(0) as u32;
match ps.line_spacing_type {
LineSpacingType::Percent => (0, ps.line_spacing, 0, value),
LineSpacingType::Fixed => (1, ps.line_spacing, 1, value),
LineSpacingType::SpaceOnly => (2, ps.line_spacing, 2, value),
LineSpacingType::Minimum => (0, 100, 3, value),
}
}
pub fn serialize_para_shape(ps: &ParaShape) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_para_shape(ps, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_para_shape<W: std::io::Write>(
ps: &ParaShape,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
let mut attr1 = ps.attr1;
let (old_type, old_value, new_type, new_value) = line_spacing_fields(ps);
attr1 &= !0x03;
attr1 |= old_type;
attr1 &= !(0x07 << 2);
attr1 |= (match ps.alignment {
crate::model::style::Alignment::Justify => 0u32,
crate::model::style::Alignment::Left => 1,
crate::model::style::Alignment::Right => 2,
crate::model::style::Alignment::Center => 3,
crate::model::style::Alignment::Distribute => 4,
crate::model::style::Alignment::Split => 5,
}) << 2;
attr1 &= !(0x03 << 23);
attr1 |= (match ps.head_type {
crate::model::style::HeadType::None => 0u32,
crate::model::style::HeadType::Outline => 1,
crate::model::style::HeadType::Number => 2,
crate::model::style::HeadType::Bullet => 3,
}) << 23;
attr1 &= !(0x07 << 25);
attr1 |= (ps.para_level.min(6) as u32) << 25;
if let Some(blw) = ps.break_latin_word.as_deref() {
let code = match blw {
"HYPHENATION" => 1u32,
"BREAK_WORD" => 2,
_ => 0, };
attr1 = (attr1 & !(0x03 << 5)) | (code << 5);
}
w.write_u32(attr1)?;
w.write_i32(ps.margin_left)?;
w.write_i32(ps.margin_right)?;
w.write_i32(ps.indent)?;
w.write_i32(ps.spacing_before)?;
w.write_i32(ps.spacing_after)?;
w.write_i32(old_value)?;
w.write_u16(ps.tab_def_id)?;
w.write_u16(ps.numbering_id)?;
w.write_u16(ps.border_fill_id)?;
for &spacing in &ps.border_spacing {
w.write_i16(spacing)?;
}
w.write_u32(ps.attr2)?;
w.write_u32((ps.attr3 & !0x1f) | new_type)?;
w.write_u32(new_value)?;
w.write_u32(ps.para_level.min(9) as u32)?;
Ok(())
}
pub fn serialize_style(style: &Style) -> Vec<u8> {
let mut w = ByteWriter::new();
write_serialize_style(style, &mut w).expect("Vec binary writer");
w.into_bytes()
}
fn write_serialize_style<W: std::io::Write>(
style: &Style,
w: &mut ByteWriter<W>,
) -> std::io::Result<()> {
w.write_hwp_string(&style.local_name)?;
w.write_hwp_string(&style.english_name)?;
w.write_u8(style.style_type)?;
w.write_u8(style.next_style_id)?;
let lang_id = if style.lang_id == 0 {
1042
} else {
style.lang_id
};
w.write_i16(lang_id)?;
w.write_u16(style.para_shape_id)?;
w.write_u16(style.char_shape_id)?;
w.write_u16(0)?;
Ok(())
}
struct RecordPos {
tag_id: u16,
#[allow(dead_code)]
level: u16,
data_size: u32,
header_offset: usize,
data_offset: usize,
total_bytes: usize,
}
#[derive(Clone)]
struct RecordScanner<'a> {
stream: &'a [u8],
offset: usize,
}
impl RecordScanner<'_> {
fn iter(&self) -> Self {
self.clone()
}
}
impl Iterator for RecordScanner<'_> {
type Item = RecordPos;
fn next(&mut self) -> Option<RecordPos> {
let start = self.offset;
let header_end = start.checked_add(4)?;
let bytes = self.stream.get(start..header_end)?;
let header = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
let mut size = header >> 20;
let data_offset = if size == 0xfff {
let end = header_end.checked_add(4)?;
let bytes = self.stream.get(header_end..end)?;
size = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
end
} else {
header_end
};
let end = data_offset.checked_add(size as usize)?;
if end > self.stream.len() {
return None;
}
self.offset = end;
Some(RecordPos {
tag_id: (header & 0x3ff) as u16,
level: ((header >> 10) & 0x3ff) as u16,
data_size: size,
header_offset: start,
data_offset,
total_bytes: end - start,
})
}
}
fn scan_records(stream: &[u8]) -> RecordScanner<'_> {
RecordScanner { stream, offset: 0 }
}
fn tag_to_id_mappings_offset(tag_id: u16) -> Option<usize> {
match tag_id {
tags::HWPTAG_BIN_DATA => Some(0),
tags::HWPTAG_BORDER_FILL => Some(32),
tags::HWPTAG_CHAR_SHAPE => Some(36),
tags::HWPTAG_TAB_DEF => Some(40),
tags::HWPTAG_NUMBERING => Some(44),
tags::HWPTAG_PARA_SHAPE => Some(52),
tags::HWPTAG_STYLE => Some(56),
_ => None,
}
}
pub fn surgical_insert_record(
raw_stream: &mut Vec<u8>,
tag_id: u16,
level: u16,
data: &[u8],
) -> Result<(), String> {
use super::record_writer::write_record;
let positions = scan_records(raw_stream);
let insert_offset = if let Some(last) = positions.iter().filter(|r| r.tag_id == tag_id).last() {
last.header_offset + last.total_bytes
} else {
if let Some(next) = positions.iter().find(|r| r.tag_id > tag_id) {
next.header_offset
} else {
raw_stream.len()
}
};
let id_mappings_info = positions
.iter()
.find(|r| r.tag_id == tags::HWPTAG_ID_MAPPINGS)
.map(|r| (r.data_offset, r.data_size));
let new_record = write_record(tag_id, level, data);
let new_len = new_record.len();
raw_stream.splice(insert_offset..insert_offset, new_record.into_iter());
if let Some((mut data_off, data_size)) = id_mappings_info {
if insert_offset <= data_off {
data_off += new_len;
}
if let Some(field_off) = tag_to_id_mappings_offset(tag_id) {
let abs = data_off + field_off;
if abs + 4 <= raw_stream.len() && field_off + 4 <= data_size as usize {
let cur = u32::from_le_bytes([
raw_stream[abs],
raw_stream[abs + 1],
raw_stream[abs + 2],
raw_stream[abs + 3],
]);
raw_stream[abs..abs + 4].copy_from_slice(&(cur + 1).to_le_bytes());
}
}
}
Ok(())
}
pub fn surgical_insert_font_all_langs(raw_stream: &mut Vec<u8>, data: &[u8]) -> Result<(), String> {
use super::record_writer::write_record;
let positions = scan_records(raw_stream);
let id_mappings = positions
.iter()
.find(|r| r.tag_id == tags::HWPTAG_ID_MAPPINGS)
.ok_or_else(|| "ID_MAPPINGS not found".to_string())?;
let idm_data_off = id_mappings.data_offset;
let idm_data_size = id_mappings.data_size as usize;
let mut lang_counts = [0u32; 7];
for lang in 0..7 {
let off = idm_data_off + 4 + lang * 4;
if off + 4 <= raw_stream.len() && 4 + lang * 4 + 4 <= idm_data_size {
lang_counts[lang] = u32::from_le_bytes([
raw_stream[off],
raw_stream[off + 1],
raw_stream[off + 2],
raw_stream[off + 3],
]);
}
}
let mut wanted = [0u64; 7];
let mut cumulative = 0u64;
for (slot, count) in wanted.iter_mut().zip(lang_counts) {
cumulative += u64::from(count);
*slot = cumulative;
}
let mut insert_points = [None; 7];
let mut ordinal = 0u64;
let mut last_face = None;
let mut last_bin = None;
for record in positions.iter() {
let end = record.header_offset + record.total_bytes;
if record.tag_id == tags::HWPTAG_BIN_DATA {
last_bin = Some(end);
}
if record.tag_id == tags::HWPTAG_FACE_NAME {
ordinal += 1;
last_face = Some(end);
for (point, wanted) in insert_points.iter_mut().zip(wanted) {
if wanted != 0 && wanted == ordinal {
*point = Some(end);
}
}
}
}
let fallback = last_face
.or(last_bin)
.unwrap_or(id_mappings.header_offset + id_mappings.total_bytes);
let insert_points = insert_points.map(|point| point.unwrap_or(fallback));
let new_record = write_record(tags::HWPTAG_FACE_NAME, 1, data);
for &point in insert_points.iter().rev() {
raw_stream.splice(point..point, new_record.iter().cloned());
}
let positions = scan_records(raw_stream);
if let Some(idm) = positions
.iter()
.find(|r| r.tag_id == tags::HWPTAG_ID_MAPPINGS)
{
for lang in 0..7usize {
let field_off = 4 + lang * 4;
let abs = idm.data_offset + field_off;
if abs + 4 <= raw_stream.len() && field_off + 4 <= idm.data_size as usize {
let cur = u32::from_le_bytes([
raw_stream[abs],
raw_stream[abs + 1],
raw_stream[abs + 2],
raw_stream[abs + 3],
]);
raw_stream[abs..abs + 4].copy_from_slice(&(cur + 1).to_le_bytes());
}
}
}
Ok(())
}
pub fn surgical_remove_records(raw_stream: &mut Vec<u8>, tag_id: u16) -> usize {
let original_len = raw_stream.len();
let mut read = 0;
let mut write = 0;
let mut removed = 0;
while let Some(record) = scan_records(&raw_stream[read..]).next() {
let end = read + record.total_bytes;
if record.tag_id == tag_id {
removed += 1;
} else {
raw_stream.copy_within(read..end, write);
write += record.total_bytes;
}
read = end;
}
raw_stream.copy_within(read..original_len, write);
raw_stream.truncate(write + original_len - read);
removed
}
pub fn surgical_update_section_count(
doc_info_stream: &mut [u8],
section_count: u16,
) -> Result<(), String> {
let positions = scan_records(doc_info_stream);
let doc_props_pos = positions
.iter()
.find(|r| r.tag_id == tags::HWPTAG_DOCUMENT_PROPERTIES)
.ok_or_else(|| "DOCUMENT_PROPERTIES 레코드를 찾을 수 없음".to_string())?;
if doc_props_pos.data_size < 2 {
return Err(format!(
"DOCUMENT_PROPERTIES 데이터 크기 부족: {} < 2",
doc_props_pos.data_size
));
}
let data_off = doc_props_pos.data_offset;
doc_info_stream[data_off..data_off + 2].copy_from_slice(§ion_count.to_le_bytes());
Ok(())
}
pub fn surgical_update_caret(
raw_stream: &mut Vec<u8>,
caret_list_id: u32,
caret_para_id: u32,
caret_char_pos: u32,
) -> Result<(), String> {
let positions = scan_records(raw_stream);
let doc_props_pos = positions
.iter()
.find(|r| r.tag_id == tags::HWPTAG_DOCUMENT_PROPERTIES)
.ok_or_else(|| "DOCUMENT_PROPERTIES 레코드를 찾을 수 없음".to_string())?;
let data_off = doc_props_pos.data_offset;
if doc_props_pos.data_size < 26 {
return Err(format!(
"DOCUMENT_PROPERTIES 데이터 크기 부족: {} < 26",
doc_props_pos.data_size
));
}
raw_stream[data_off + 14..data_off + 18].copy_from_slice(&caret_list_id.to_le_bytes());
raw_stream[data_off + 18..data_off + 22].copy_from_slice(&caret_para_id.to_le_bytes());
raw_stream[data_off + 22..data_off + 26].copy_from_slice(&caret_char_pos.to_le_bytes());
Ok(())
}
#[cfg(test)]
mod tests;