use std::io::Write;
use crate::model::bin_data::BinDataContent;
use crate::model::bin_data::{BinData, BinDataType, MAX_BIN_DATA_BYTES};
use crate::model::document::{Document, Preview};
use crate::password_crypto::{encrypt_hwp5_stream, HWP5_ENCRYPT_VERSION};
use super::body_text::serialize_section_for_version;
use super::content_loss::{
ContentLoss, ContentLossReason, ContentLossReport, SerializedDocument, SerializedFormat,
};
use super::doc_info::{serialize_doc_info, surgical_update_section_count};
use super::header::serialize_file_header;
use super::mini_cfb;
use super::SerializeError;
#[derive(Clone, Copy)]
enum ContentLossWarningMode {
ReportOnly,
LegacyStderr,
}
pub fn serialize_hwp(doc: &Document) -> Result<Vec<u8>, SerializeError> {
let serialized = serialize_hwp_inner(doc, None, ContentLossWarningMode::LegacyStderr)?;
Ok(serialized.into_bytes())
}
pub fn serialize_hwp_with_report(doc: &Document) -> Result<SerializedDocument, SerializeError> {
serialize_hwp_inner(doc, None, ContentLossWarningMode::ReportOnly)
}
pub fn serialize_hwp_with_password(
doc: &Document,
password: &[u8],
) -> Result<Vec<u8>, SerializeError> {
let serialized =
serialize_hwp_inner(doc, Some(password), ContentLossWarningMode::LegacyStderr)?;
Ok(serialized.into_bytes())
}
pub fn serialize_hwp_with_password_and_report(
doc: &Document,
password: &[u8],
) -> Result<SerializedDocument, SerializeError> {
serialize_hwp_inner(doc, Some(password), ContentLossWarningMode::ReportOnly)
}
fn serialize_hwp_inner(
doc: &Document,
password: Option<&[u8]>,
warning_mode: ContentLossWarningMode,
) -> Result<SerializedDocument, SerializeError> {
serialize_hwp_inner_with_storage(
doc,
password,
warning_mode,
&crate::storage::Unbounded,
usize::MAX,
)
}
#[cfg(feature = "pdf-import")]
pub(crate) fn serialize_hwp_with_storage<S: crate::storage::Storage>(
doc: &Document,
storage: &S,
maximum: usize,
) -> Result<Vec<u8>, SerializeError>
where
S::Error: std::fmt::Display,
{
Ok(serialize_hwp_inner_with_storage(
doc,
None,
ContentLossWarningMode::LegacyStderr,
storage,
maximum,
)?
.into_bytes())
}
fn serialize_hwp_inner_with_storage<S: crate::storage::Storage>(
doc: &Document,
password: Option<&[u8]>,
warning_mode: ContentLossWarningMode,
storage: &S,
maximum: usize,
) -> Result<SerializedDocument, SerializeError>
where
S::Error: std::fmt::Display,
{
crate::model::section_tail::validate_preservation(doc)
.map_err(SerializeError::UnsupportedInput)?;
let storage_error = |error| SerializeError::CfbError(format!("{error}"));
storage
.bytes(
doc.header
.raw_data
.as_ref()
.map_or(256, |raw| raw.len().max(256)),
)
.map_err(storage_error)?;
let header_bytes = if let Some(_) = password {
let mut header = doc.header.clone();
header.distribution = false;
header.encrypted = true;
header.flags = (header.flags | 0x02) & !0x04;
if let Some(raw) = header.raw_data.as_mut() {
if raw.len() >= 48 {
raw[36..40].copy_from_slice(&header.flags.to_le_bytes());
raw[44..48].copy_from_slice(&HWP5_ENCRYPT_VERSION.to_le_bytes());
}
}
let mut bytes = serialize_file_header(&header);
bytes[36..40].copy_from_slice(&header.flags.to_le_bytes());
bytes[44..48].copy_from_slice(&HWP5_ENCRYPT_VERSION.to_le_bytes());
bytes
} else if doc.header.distribution || doc.header.encrypted {
let mut header = doc.header.clone();
header.distribution = false;
header.encrypted = false;
header.flags &= !0x06;
if let Some(raw) = header.raw_data.as_mut() {
if raw.len() >= 40 {
let flags = u32::from_le_bytes([raw[36], raw[37], raw[38], raw[39]]) & !0x06u32;
raw[36..40].copy_from_slice(&flags.to_le_bytes());
}
if doc.header.encrypted && raw.len() >= 48 {
raw[44..48].fill(0);
}
}
serialize_file_header(&header)
} else {
serialize_file_header(&doc.header)
};
let output_version = u32::from_le_bytes(header_bytes[32..36].try_into().unwrap());
let split_multi_sec_pr = doc.layout_profile().hwpx_stored_layout();
let mut section_bytes_list = Vec::new();
let mut viewtext_history = Vec::new();
let previous_line_seg_sections = doc
.extra_streams
.iter()
.find(|(path, _)| path == crate::model::line_seg_tags::HWP_STREAM)
.map(|(_, bytes)| crate::model::line_seg_tags::decode(bytes))
.unwrap_or_default();
let mut rhwp_line_seg_sections = Vec::new();
let mut record_line_seg_semantics = |section: &crate::model::document::Section,
bytes: &[u8]| {
let digest = crate::model::line_seg_tags::section_digest(bytes);
let reused_source = section.raw_stream.as_deref() == Some(bytes);
if !reused_source || previous_line_seg_sections.contains(&digest) {
rhwp_line_seg_sections.push(digest);
}
};
let mut form_id_allocator = None;
let memos =
crate::model::section_tail::collect(&doc.sections, storage).map_err(storage_error)?;
for (section_idx, section) in doc.sections.iter().enumerate() {
let tail: &[_] = if section_idx + 1 == doc.sections.len() {
&memos
} else {
&[]
};
let split_starts: Vec<usize> =
if !split_multi_sec_pr || section.raw_provenance_permits_reuse() {
Vec::new()
} else {
section
.paragraphs
.iter()
.enumerate()
.skip(1)
.filter(|(_, p)| {
p.controls
.iter()
.any(|c| matches!(c, crate::model::control::Control::SectionDef(_)))
})
.map(|(i, _)| i)
.collect()
};
if split_starts.is_empty() {
let prepared =
super::form_identity::prepare_section(section, doc, &mut form_id_allocator)?;
let prepared = super::hwpx_lineage_lines::prepare_section(prepared, doc);
let bytes = super::body_text::try_serialize_section_for_version(
&prepared,
output_version,
tail,
storage,
)
.map_err(storage_error)?;
if prepared.raw_provenance_permits_reuse() {
if let Some(visible) =
crate::parser::tracked_viewtext::project(&bytes, &doc.doc_info)
.map_err(|error| SerializeError::UnsupportedInput(error.to_string()))?
{
record_line_seg_semantics(section, &bytes);
viewtext_history.push((section_bytes_list.len(), bytes));
section_bytes_list.push(visible);
continue;
}
}
record_line_seg_semantics(section, &bytes);
section_bytes_list.push(bytes);
continue;
}
let mut starts = Vec::with_capacity(split_starts.len() + 1);
starts.push(0usize);
starts.extend(split_starts);
for (k, &start) in starts.iter().enumerate() {
let end = starts
.get(k + 1)
.copied()
.unwrap_or(section.paragraphs.len());
let paragraphs = section.paragraphs[start..end].to_vec();
let section_def = paragraphs
.first()
.and_then(|p| {
p.controls.iter().find_map(|c| match c {
crate::model::control::Control::SectionDef(sd) => Some((**sd).clone()),
_ => None,
})
})
.unwrap_or_else(|| section.section_def.clone());
let sub = crate::model::document::Section {
section_def,
paragraphs,
trailing_lists: if k + 1 == starts.len() {
section.trailing_lists.clone()
} else {
None
},
raw_stream: None,
raw_provenance: None,
};
let prepared =
super::form_identity::prepare_section(&sub, doc, &mut form_id_allocator)?;
let prepared = super::hwpx_lineage_lines::prepare_section(prepared, doc);
let bytes = super::body_text::try_serialize_section_for_version(
&prepared,
output_version,
if k + 1 == starts.len() { tail } else { &[] },
storage,
)
.map_err(storage_error)?;
record_line_seg_semantics(&sub, &bytes);
section_bytes_list.push(bytes);
}
}
let emitted_sections = section_bytes_list.len().min(u16::MAX as usize) as u16;
let mut doc_info_bytes =
super::doc_info::try_serialize_doc_info(&doc.doc_info, &doc.doc_properties, storage)
.map_err(storage_error)?;
if doc.doc_properties.section_count != emitted_sections {
if surgical_update_section_count(&mut doc_info_bytes, emitted_sections).is_err() {
let mut props = doc.doc_properties.clone();
props.section_count = emitted_sections;
props.raw_data = None;
doc_info_bytes =
super::doc_info::try_serialize_doc_info(&doc.doc_info, &props, storage)
.map_err(storage_error)?;
}
}
let compressed = doc.header.compressed;
let preview = supplement_preview(doc);
let mut content_loss = ContentLossReport::new(SerializedFormat::Hwp);
let mut extra_streams = storage
.clone_record(&doc.extra_streams)
.map_err(storage_error)?;
for (path, bytes) in &mut extra_streams {
if path.trim_start_matches('/') == "Scripts/DefaultJScript" {
if let Some(converted) =
crate::model::form_script::script_stream_for_hwp(doc, bytes, compressed)
.map_err(|error| SerializeError::UnsupportedInput(error.to_string()))?
{
*bytes = converted;
}
}
}
extra_streams.retain(|(path, _)| path != crate::model::line_seg_tags::HWP_STREAM);
if !rhwp_line_seg_sections.is_empty() {
extra_streams.push((
crate::model::line_seg_tags::HWP_STREAM.to_string(),
crate::model::line_seg_tags::encode(&rhwp_line_seg_sections),
));
}
extra_streams.retain(|(path, _)| path != crate::model::border_paint::HWP_STREAM);
if let Some(bytes) = crate::model::border_paint::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
storage
.push(
&mut extra_streams,
(
storage
.string(crate::model::border_paint::HWP_STREAM)
.map_err(storage_error)?,
bytes,
),
)
.map_err(storage_error)?;
content_loss
.record_with_storage(
crate::model::border_paint::native_editing_loss_with_storage(storage)
.map_err(storage_error)?,
storage,
)
.map_err(storage_error)?;
}
extra_streams.retain(|(path, _)| path != crate::model::text_clip::HWP_STREAM);
if let Some(bytes) = crate::model::text_clip::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
storage
.push(
&mut extra_streams,
(
storage
.string(crate::model::text_clip::HWP_STREAM)
.map_err(storage_error)?,
bytes,
),
)
.map_err(storage_error)?;
content_loss
.record_with_storage(
crate::model::text_clip::native_visibility_loss_with_storage(storage)
.map_err(storage_error)?,
storage,
)
.map_err(storage_error)?;
}
extra_streams.retain(|(path, _)| path != crate::model::text_paint::HWP_STREAM);
if let Some(bytes) = crate::model::text_paint::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
storage
.push(
&mut extra_streams,
(
storage
.string(crate::model::text_paint::HWP_STREAM)
.map_err(storage_error)?,
bytes,
),
)
.map_err(storage_error)?;
content_loss
.record_with_storage(
crate::model::text_paint::native_visibility_loss_with_storage(storage)
.map_err(storage_error)?,
storage,
)
.map_err(storage_error)?;
}
if doc.layout_profile().hwp3_external_realign()
&& !extra_streams
.iter()
.any(|(path, _)| path == crate::model::document::HWP3_EXTERNAL_REALIGN_STREAM_PATH)
{
extra_streams.push((
crate::model::document::HWP3_EXTERNAL_REALIGN_STREAM_PATH.to_string(),
b"1".to_vec(),
));
}
extra_streams.retain(|(path, _)| path != crate::model::native_font_program::HWP_STREAM);
if let Some(bytes) = crate::model::native_font_program::encode_with_storage(
&doc.doc_info,
&doc_info_bytes,
storage,
)
.map_err(SerializeError::UnsupportedInput)?
{
storage
.push(
&mut extra_streams,
(
storage
.string(crate::model::native_font_program::HWP_STREAM)
.map_err(storage_error)?,
bytes,
),
)
.map_err(storage_error)?;
}
extra_streams.retain(|(path, _)| path != crate::model::hyperlink_format::HWP_STREAM);
if let Some(bytes) = crate::model::hyperlink_format::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
storage
.push(
&mut extra_streams,
(
storage
.string(crate::model::hyperlink_format::HWP_STREAM)
.map_err(storage_error)?,
bytes,
),
)
.map_err(storage_error)?;
}
let memo_links = crate::model::memo_extended::live_links(doc);
if !memo_links.is_empty() {
extra_streams.retain(|(path, _)| path != crate::model::memo_extended::HWP_STREAM);
let record = crate::model::memo_extended::encode_hwp(&memo_links);
let bytes = if compressed {
compress_stream_with_storage(&record, storage)?
} else {
record
};
storage
.push(
&mut extra_streams,
(
storage
.string(crate::model::memo_extended::HWP_STREAM)
.map_err(storage_error)?,
bytes,
),
)
.map_err(storage_error)?;
}
let bytes = write_hwp_cfb_with_storage(
&header_bytes,
&doc_info_bytes,
§ion_bytes_list,
&viewtext_history,
&doc.doc_info.bin_data_list,
&doc.bin_data_content,
&preview,
&extra_streams,
compressed,
password,
&mut content_loss,
storage,
maximum,
)?;
if matches!(warning_mode, ContentLossWarningMode::LegacyStderr) {
content_loss.write_warnings_to_stderr();
}
Ok(SerializedDocument::new(bytes, content_loss))
}
fn supplement_preview(doc: &Document) -> Option<Preview> {
let has_real_text = doc
.preview
.as_ref()
.and_then(|p| p.text.as_ref())
.map(|t| !t.trim().is_empty())
.unwrap_or(false);
if has_real_text {
return doc.preview.clone();
}
let text = build_preview_text(doc);
if text.trim().is_empty() {
return doc.preview.clone();
}
Some(Preview {
image: doc.preview.as_ref().and_then(|p| p.image.clone()),
text: Some(text),
})
}
fn build_preview_text(doc: &Document) -> String {
const MAX_CHARS: usize = 1000;
let mut out = String::new();
for section in &doc.sections {
for para in §ion.paragraphs {
let line = para.text.trim_end_matches('\u{0}');
if line.is_empty() {
continue;
}
out.push_str(line);
out.push_str("\r\n");
if out.chars().count() >= MAX_CHARS {
return out.chars().take(MAX_CHARS).collect();
}
}
}
out
}
fn compress_stream(data: &[u8]) -> Result<Vec<u8>, SerializeError> {
compress_stream_with_storage(data, &crate::storage::Unbounded)
}
fn compress_stream_with_storage<S: crate::storage::Storage>(
data: &[u8],
storage: &S,
) -> Result<Vec<u8>, SerializeError>
where
S::Error: std::fmt::Display,
{
use flate2::write::DeflateEncoder;
use flate2::Compression;
let mut encoder = DeflateEncoder::new(
super::budget_cursor::BudgetCursor::new(storage, usize::MAX),
Compression::default(),
);
encoder
.write_all(data)
.map_err(|e| SerializeError::CompressError(e.to_string()))?;
encoder
.finish()
.map(|writer| writer.into_inner())
.map_err(|e| SerializeError::CompressError(e.to_string()))
}
fn write_hwp_cfb(
header_bytes: &[u8],
doc_info_bytes: &[u8],
section_bytes_list: &[Vec<u8>],
viewtext_history: &[(usize, Vec<u8>)],
bin_data_list: &[BinData],
bin_data_content: &[BinDataContent],
preview: &Option<Preview>,
extra_streams: &[(String, Vec<u8>)],
compressed: bool,
password: Option<&[u8]>,
content_loss: &mut ContentLossReport,
) -> Result<Vec<u8>, SerializeError> {
write_hwp_cfb_with_storage(
header_bytes,
doc_info_bytes,
section_bytes_list,
viewtext_history,
bin_data_list,
bin_data_content,
preview,
extra_streams,
compressed,
password,
content_loss,
&crate::storage::Unbounded,
usize::MAX,
)
}
fn write_hwp_cfb_with_storage<S: crate::storage::Storage>(
header_bytes: &[u8],
doc_info_bytes: &[u8],
section_bytes_list: &[Vec<u8>],
viewtext_history: &[(usize, Vec<u8>)],
bin_data_list: &[BinData],
bin_data_content: &[BinDataContent],
preview: &Option<Preview>,
extra_streams: &[(String, Vec<u8>)],
compressed: bool,
password: Option<&[u8]>,
content_loss: &mut ContentLossReport,
storage: &S,
maximum: usize,
) -> Result<Vec<u8>, SerializeError>
where
S::Error: std::fmt::Display,
{
let storage_error = |error| SerializeError::CfbError(format!("{error}"));
storage.bytes(0).map_err(storage_error)?;
let mut streams: Vec<(String, Vec<u8>)> = Vec::new();
storage
.push(
&mut streams,
(
storage.string("/FileHeader").map_err(storage_error)?,
storage.copy_slice(header_bytes).map_err(storage_error)?,
),
)
.map_err(storage_error)?;
let doc_info_data = if compressed {
compress_stream_with_storage(doc_info_bytes, storage)?
} else {
storage.copy_slice(doc_info_bytes).map_err(storage_error)?
};
storage
.push(
&mut streams,
(
storage.string("/DocInfo").map_err(storage_error)?,
encrypt_if_password(doc_info_data, password),
),
)
.map_err(storage_error)?;
for (i, section_bytes) in section_bytes_list.iter().enumerate() {
let path = storage
.display(&format_args!("/BodyText/Section{}", i))
.map_err(storage_error)?;
let data = if compressed {
compress_stream_with_storage(section_bytes, storage)?
} else {
storage.copy_slice(section_bytes).map_err(storage_error)?
};
storage
.push(&mut streams, (path, encrypt_if_password(data, password)))
.map_err(storage_error)?;
}
for (index, bytes) in viewtext_history {
let data = if compressed {
compress_stream_with_storage(bytes, storage)?
} else {
storage.copy_slice(bytes).map_err(storage_error)?
};
storage
.push(
&mut streams,
(
storage
.display(&format_args!("/ViewText/Section{index}"))
.map_err(storage_error)?,
encrypt_if_password(data, password),
),
)
.map_err(storage_error)?;
}
const CFB_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
for (index, content) in bin_data_content.iter().enumerate() {
if crate::model::bin_data::is_hwp5_link_slot(content, bin_data_list.get(index)) {
continue;
}
let (storage_id, ext, mut should_compress) =
find_bin_data_info_with_compress(bin_data_list, content, compressed);
if password.is_some() {
should_compress = compressed;
}
let storage_name = storage
.display(&format_args!("BIN{:04X}.{}", storage_id, ext))
.map_err(storage_error)?;
let path = storage
.display(&format_args!("/BinData/{}", storage_name))
.map_err(storage_error)?;
if let Some(stored) = content
.data
.load_raw()
.filter(|stored| stored.compressed == should_compress)
{
streams.push((path, encrypt_if_password(stored.bytes, password)));
continue;
}
let bytes = match storage
.bin_data(&content.data, MAX_BIN_DATA_BYTES)
.map_err(storage_error)?
{
Some(bytes) => bytes,
None => match content.data.load_raw() {
Some(stored) if stored.compressed == should_compress => {
storage
.push(
&mut streams,
(path, encrypt_if_password(stored.bytes, password)),
)
.map_err(storage_error)?;
continue;
}
Some(_) => {
content_loss
.record_with_storage(
ContentLoss::binary_content_emptied(
storage_id,
storage.string(&path).map_err(storage_error)?,
ContentLossReason::StoredCompressionMismatch,
),
storage,
)
.map_err(storage_error)?;
storage
.push(
&mut streams,
(path, encrypt_if_password(Vec::new(), password)),
)
.map_err(storage_error)?;
continue;
}
None => {
content_loss
.record_with_storage(
ContentLoss::binary_content_emptied(
storage_id,
storage.string(&path).map_err(storage_error)?,
ContentLossReason::RawPassthroughUnavailable,
),
storage,
)
.map_err(storage_error)?;
storage
.push(
&mut streams,
(path, encrypt_if_password(Vec::new(), password)),
)
.map_err(storage_error)?;
continue;
}
},
};
let is_ole_storage = bytes.len() >= 8
&& bytes[..8] == CFB_MAGIC
&& bin_data_list
.iter()
.any(|bd| bd.data_type == BinDataType::Storage && bd.storage_id == content.id);
let payload: Vec<u8> = if is_ole_storage {
let mut v = storage
.vec(bytes.len().saturating_add(4))
.map_err(storage_error)?;
v.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
v.extend_from_slice(&bytes);
v
} else {
bytes
};
let data = if should_compress {
match compress_stream_with_storage(&payload, storage) {
Ok(bytes) => bytes,
Err(_) => {
storage.bytes(0).map_err(storage_error)?;
storage.copy_slice(&payload).map_err(storage_error)?
}
}
} else {
payload
};
storage
.push(&mut streams, (path, encrypt_if_password(data, password)))
.map_err(storage_error)?;
}
if let Some(ref prv) = preview {
if let Some(ref image) = prv.image {
storage
.push(
&mut streams,
(
storage.string("/PrvImage").map_err(storage_error)?,
storage.copy_slice(&image.data).map_err(storage_error)?,
),
)
.map_err(storage_error)?;
}
if let Some(ref text) = prv.text {
let utf16 = text.encode_utf16();
let count = text.encode_utf16().count().saturating_mul(2);
let mut bytes = storage.vec(count).map_err(storage_error)?;
for ch in utf16 {
bytes.extend_from_slice(&ch.to_le_bytes());
}
storage
.push(
&mut streams,
(storage.string("/PrvText").map_err(storage_error)?, bytes),
)
.map_err(storage_error)?;
}
}
for (path, data) in extra_streams {
let payload = if password.is_some()
&& (path.starts_with("/Scripts/") || path.starts_with("/BinData/"))
{
encrypt_if_password(storage.copy_slice(data).map_err(storage_error)?, password)
} else {
storage.copy_slice(data).map_err(storage_error)?
};
storage
.push(
&mut streams,
(storage.string(path).map_err(storage_error)?, payload),
)
.map_err(storage_error)?;
}
let named_streams = storage
.collect(
streams
.iter()
.map(|(path, data)| (path.as_str(), data.as_slice())),
)
.map_err(storage_error)?;
mini_cfb::build_cfb_with_storage(&named_streams, [0; 16], storage, maximum)
.map_err(SerializeError::CfbError)
}
fn encrypt_if_password(data: Vec<u8>, password: Option<&[u8]>) -> Vec<u8> {
match password {
Some(value) => encrypt_hwp5_stream(&data, value),
None => data,
}
}
fn find_bin_data_info_with_compress<'a>(
bin_data_list: &'a [BinData],
content: &'a BinDataContent,
doc_compressed: bool,
) -> (u16, &'a str, bool) {
use crate::model::bin_data::BinDataCompression;
for bd in bin_data_list {
if matches!(bd.data_type, BinDataType::Embedding | BinDataType::Storage)
&& bd.storage_id == content.id
{
let ext = bd.extension.as_deref().unwrap_or("dat");
let should_compress = match bd.compression {
BinDataCompression::Default => doc_compressed,
BinDataCompression::Compress => true,
BinDataCompression::NoCompress => false,
};
return (bd.storage_id, ext, should_compress);
}
}
(content.id, &content.extension, doc_compressed)
}
#[cfg(test)]
mod tests;