use super::clipboard::{
clip_paragraph_text_range_for_clipboard, strip_structural_controls_for_text_clipboard,
};
use super::formatting::{
char_shape_mods_affect_text_flow, para_shape_mods_affect_text_flow, restore_para_meta,
};
use crate::document_core::helpers::{
build_tab_def_from_json, json_has_border_keys, json_has_tab_keys, parse_char_shape_mods,
parse_json_i16_array, parse_para_shape_mods,
};
use crate::document_core::{
header_footer_apply_from_u8, header_footer_apply_to_u8, ClipboardData, DocumentCore,
};
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;
use crate::model::header_footer::{Footer, Header, HeaderFooterApply};
use crate::model::paragraph::{ParaMeta, Paragraph};
use crate::renderer::composer::{reflow_line_segs, restamp_indentation, ParagraphBox};
fn apply_label(a: HeaderFooterApply) -> &'static str {
match a {
HeaderFooterApply::Both => "양 쪽",
HeaderFooterApply::Even => "짝수 쪽",
HeaderFooterApply::Odd => "홀수 쪽",
}
}
impl DocumentCore {
pub fn get_header_footer_preview_page_native(
&self,
section_idx: usize,
) -> Result<String, HwpError> {
let page_index = self.header_footer_preview_page_for_section(section_idx)?;
Ok(format!(
"{{\"ok\":true,\"pageIndex\":{},\"sectionIdx\":{}}}",
page_index, section_idx
))
}
pub fn get_header_footer_native(
&self,
section_idx: usize,
is_header: bool,
apply_to: u8,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과 (총 {}개)",
section_idx,
self.document.sections.len()
)));
}
let apply = header_footer_apply_from_u8(apply_to);
if let Some((pi, ci)) = self.find_header_footer_control(section_idx, is_header, apply) {
let section = &self.document.sections[section_idx];
let ctrl = §ion.paragraphs[pi].controls[ci];
let (paragraphs, at) = match ctrl {
Control::Header(h) => (&h.paragraphs, h.apply_to),
Control::Footer(f) => (&f.paragraphs, f.apply_to),
_ => unreachable!(),
};
let text: String = paragraphs
.iter()
.map(|p| p.text.clone())
.collect::<Vec<_>>()
.join("\n");
let kind = if is_header { "header" } else { "footer" };
let label = apply_label(at);
Ok(format!(
"{{\"ok\":true,\"exists\":true,\"kind\":\"{}\",\"applyTo\":{},\"label\":\"{}\",\"paraIndex\":{},\"controlIndex\":{},\"paraCount\":{},\"text\":\"{}\"}}",
kind, header_footer_apply_to_u8(at), label, pi, ci, paragraphs.len(),
super::super::helpers::json_escape(&text)
))
} else {
Ok(format!("{{\"ok\":true,\"exists\":false}}"))
}
}
pub fn create_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과 (총 {}개)",
section_idx,
self.document.sections.len()
)));
}
let apply = header_footer_apply_from_u8(apply_to);
if self
.find_header_footer_control(section_idx, is_header, apply)
.is_some()
{
let kind = if is_header { "머리말" } else { "꼬리말" };
return Err(HwpError::RenderError(format!(
"이미 {}({})이 존재합니다",
kind,
apply_label(apply)
)));
}
let empty_para = Paragraph::default();
let ctrl = if is_header {
Control::Header(Box::new(Header {
apply_to: apply,
paragraphs: vec![empty_para],
raw_attr: apply_to as u32,
raw_ctrl_extra: Vec::new(),
..Default::default()
}))
} else {
Control::Footer(Box::new(Footer {
apply_to: apply,
paragraphs: vec![empty_para],
raw_attr: apply_to as u32,
raw_ctrl_extra: Vec::new(),
..Default::default()
}))
};
let section = &mut self.document.sections[section_idx];
if section.paragraphs.is_empty() {
return Err(HwpError::RenderError("구역에 문단이 없습니다".to_string()));
}
section.paragraphs[0].controls.push(ctrl);
section.paragraphs[0].align_ctrl_data_records();
section.paragraphs[0].char_count += 8;
section.raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.expect("방금 생성한 컨트롤을 찾을 수 없음");
let kind = if is_header { "header" } else { "footer" };
let label = apply_label(apply);
Ok(format!(
"{{\"ok\":true,\"kind\":\"{}\",\"applyTo\":{},\"label\":\"{}\",\"paraIndex\":{},\"controlIndex\":{}}}",
kind, apply_to, label, pi, ci
))
}
fn get_hf_paragraph_mut(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
) -> Result<&mut Paragraph, HwpError> {
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
let kind = if is_header { "머리말" } else { "꼬리말" };
HwpError::RenderError(format!(
"{}({})이 존재하지 않습니다",
kind,
apply_label(apply)
))
})?;
let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
match ctrl {
Control::Header(h) => {
if hf_para_idx >= h.paragraphs.len() {
return Err(HwpError::RenderError(format!(
"머리말 문단 인덱스 {} 범위 초과 (총 {}개)",
hf_para_idx,
h.paragraphs.len()
)));
}
Ok(&mut h.paragraphs[hf_para_idx])
}
Control::Footer(f) => {
if hf_para_idx >= f.paragraphs.len() {
return Err(HwpError::RenderError(format!(
"꼬리말 문단 인덱스 {} 범위 초과 (총 {}개)",
hf_para_idx,
f.paragraphs.len()
)));
}
Ok(&mut f.paragraphs[hf_para_idx])
}
_ => Err(HwpError::RenderError(
"컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
)),
}
}
fn get_hf_paragraph_ref(
&self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
) -> Option<&Paragraph> {
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self.find_header_footer_control(section_idx, is_header, apply)?;
let ctrl = &self.document.sections[section_idx].paragraphs[pi].controls[ci];
match ctrl {
Control::Header(h) => h.paragraphs.get(hf_para_idx),
Control::Footer(f) => f.paragraphs.get(hf_para_idx),
_ => None,
}
}
pub(crate) fn get_hf_paragraphs_ref(
&self,
section_idx: usize,
is_header: bool,
apply_to: u8,
) -> Result<&[Paragraph], HwpError> {
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
HwpError::RenderError("머리말/꼬리말 정의를 찾을 수 없음".to_string())
})?;
match &self.document.sections[section_idx].paragraphs[pi].controls[ci] {
Control::Header(header) => Ok(&header.paragraphs),
Control::Footer(footer) => Ok(&footer.paragraphs),
_ => Err(HwpError::RenderError(
"컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
)),
}
}
fn get_hf_paragraphs_mut(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
) -> Result<&mut Vec<Paragraph>, HwpError> {
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
HwpError::RenderError("머리말/꼬리말 정의를 찾을 수 없음".to_string())
})?;
match &mut self.document.sections[section_idx].paragraphs[pi].controls[ci] {
Control::Header(header) => Ok(&mut header.paragraphs),
Control::Footer(footer) => Ok(&mut footer.paragraphs),
_ => Err(HwpError::RenderError(
"컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
)),
}
}
pub fn insert_text_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
char_offset: usize,
text: &str,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과 (총 {}개)",
section_idx,
self.document.sections.len()
)));
}
let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
let new_chars_count = text.chars().count();
let inserted_at = hf_para.insert_text_at(char_offset, text);
self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
self.document.sections[section_idx].raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
let new_offset = inserted_at + new_chars_count;
self.event_log
.push(DocumentEvent::HeaderFooterTextReplaced {
section: section_idx,
is_header,
apply_to,
start_para: hf_para_idx,
start_offset: inserted_at,
end_para: hf_para_idx,
end_offset: inserted_at,
inserted_end_para: hf_para_idx,
inserted_end_offset: new_offset,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"charOffset\":{}",
new_offset
)))
}
pub fn delete_text_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
char_offset: usize,
count: usize,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과 (총 {}개)",
section_idx,
self.document.sections.len()
)));
}
let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
let actual_offset = char_offset.min(hf_para.text.chars().count());
let deleted_text: String = hf_para
.text
.chars()
.skip(actual_offset)
.take(count)
.collect();
hf_para.delete_text_at(actual_offset, count);
self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
self.document.sections[section_idx].raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
let deleted_count = deleted_text.chars().count();
self.event_log
.push(DocumentEvent::HeaderFooterTextReplaced {
section: section_idx,
is_header,
apply_to,
start_para: hf_para_idx,
start_offset: actual_offset,
end_para: hf_para_idx,
end_offset: actual_offset + deleted_count,
inserted_end_para: hf_para_idx,
inserted_end_offset: actual_offset,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"charOffset\":{},\"deletedText\":\"{}\"",
actual_offset,
super::super::helpers::json_escape(&deleted_text)
)))
}
pub fn split_paragraph_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
char_offset: usize,
restore_meta: Option<ParaMeta>,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과",
section_idx
)));
}
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
let kind = if is_header { "머리말" } else { "꼬리말" };
HwpError::RenderError(format!("{}이 존재하지 않습니다", kind))
})?;
let new_para = {
let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
let paragraphs = match ctrl {
Control::Header(h) => &mut h.paragraphs,
Control::Footer(f) => &mut f.paragraphs,
_ => return Err(HwpError::RenderError("컨트롤 타입 불일치".to_string())),
};
if hf_para_idx >= paragraphs.len() {
return Err(HwpError::RenderError(format!(
"문단 인덱스 {} 범위 초과",
hf_para_idx
)));
}
let mut new_para = paragraphs[hf_para_idx].split_at(char_offset);
if let Some(meta) = restore_meta {
restore_para_meta(&mut new_para, meta, &self.document.doc_info.para_shapes);
}
new_para
};
let new_para_idx = hf_para_idx + 1;
{
let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
let paragraphs = match ctrl {
Control::Header(h) => &mut h.paragraphs,
Control::Footer(f) => &mut f.paragraphs,
_ => unreachable!(),
};
paragraphs.insert(new_para_idx, new_para);
}
self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
self.reflow_hf_paragraph(section_idx, is_header, apply_to, new_para_idx);
self.document.sections[section_idx].raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
self.event_log.push(DocumentEvent::ParagraphSplit {
section: section_idx,
para: hf_para_idx,
offset: char_offset,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"hfParaIndex\":{},\"charOffset\":0",
new_para_idx
)))
}
pub fn merge_paragraph_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과",
section_idx
)));
}
if hf_para_idx == 0 {
return Err(HwpError::RenderError(
"첫 번째 문단은 이전 문단과 병합할 수 없습니다".to_string(),
));
}
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
let kind = if is_header { "머리말" } else { "꼬리말" };
HwpError::RenderError(format!("{}이 존재하지 않습니다", kind))
})?;
let merge_offset;
let removed_meta;
{
let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
let paragraphs = match ctrl {
Control::Header(h) => &mut h.paragraphs,
Control::Footer(f) => &mut f.paragraphs,
_ => return Err(HwpError::RenderError("컨트롤 타입 불일치".to_string())),
};
if hf_para_idx >= paragraphs.len() {
return Err(HwpError::RenderError(format!(
"문단 인덱스 {} 범위 초과",
hf_para_idx
)));
}
merge_offset = paragraphs[hf_para_idx - 1].text.chars().count();
let removed = paragraphs.remove(hf_para_idx);
removed_meta = super::super::helpers::removed_para_meta_field(&removed.capture_meta());
paragraphs[hf_para_idx - 1].merge_from(&removed);
}
let prev_idx = hf_para_idx - 1;
self.reflow_hf_paragraph(section_idx, is_header, apply_to, prev_idx);
self.document.sections[section_idx].raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
self.event_log.push(DocumentEvent::ParagraphMerged {
section: section_idx,
para: hf_para_idx,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"hfParaIndex\":{},\"charOffset\":{}{}",
prev_idx, merge_offset, removed_meta
)))
}
pub fn get_header_footer_para_info_native(
&self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과",
section_idx
)));
}
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
let kind = if is_header { "머리말" } else { "꼬리말" };
HwpError::RenderError(format!("{}이 존재하지 않습니다", kind))
})?;
let ctrl = &self.document.sections[section_idx].paragraphs[pi].controls[ci];
let paragraphs = match ctrl {
Control::Header(h) => &h.paragraphs,
Control::Footer(f) => &f.paragraphs,
_ => return Err(HwpError::RenderError("컨트롤 타입 불일치".to_string())),
};
let para_count = paragraphs.len();
let (char_count, text) = if let Some(paragraph) = paragraphs.get(hf_para_idx) {
(paragraph.text.chars().count(), paragraph.text.as_str())
} else {
(0, "")
};
Ok(format!(
"{{\"ok\":true,\"paraCount\":{},\"charCount\":{},\"text\":\"{}\"}}",
para_count,
char_count,
super::super::helpers::json_escape(text)
))
}
#[allow(clippy::too_many_arguments)]
pub fn replace_range_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
start_hf_para_idx: usize,
start_char_offset: usize,
end_hf_para_idx: usize,
end_char_offset: usize,
replacement_text: &str,
) -> Result<String, HwpError> {
let ((start_para, start_offset), (end_para, end_offset)) =
if (start_hf_para_idx, start_char_offset) > (end_hf_para_idx, end_char_offset) {
(
(end_hf_para_idx, end_char_offset),
(start_hf_para_idx, start_char_offset),
)
} else {
(
(start_hf_para_idx, start_char_offset),
(end_hf_para_idx, end_char_offset),
)
};
{
let paragraphs = self.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?;
if start_para >= paragraphs.len() || end_para >= paragraphs.len() {
return Err(HwpError::RenderError(format!(
"머리말/꼬리말 문단 범위 초과 (start={}, end={}, total={})",
start_para,
end_para,
paragraphs.len()
)));
}
let start_len = paragraphs[start_para].text.chars().count();
let end_len = paragraphs[end_para].text.chars().count();
if start_offset > start_len || end_offset > end_len {
return Err(HwpError::RenderError(format!(
"머리말/꼬리말 문자 범위 초과 (start={}/{}, end={}/{})",
start_offset, start_len, end_offset, end_len
)));
}
}
let normalized = replacement_text.replace("\r\n", "\n").replace('\r', "\n");
let lines: Vec<&str> = normalized.split('\n').collect();
let (cursor_para, cursor_offset);
{
let paragraphs = self.get_hf_paragraphs_mut(section_idx, is_header, apply_to)?;
let suffix = {
let mut end_snapshot = paragraphs[end_para].clone();
end_snapshot.split_at(end_offset)
};
let _discarded_tail = paragraphs[start_para].split_at(start_offset);
if end_para > start_para {
paragraphs.drain((start_para + 1)..=end_para);
}
paragraphs[start_para].insert_text_at(start_offset, lines[0]);
let mut result_para = start_para;
if lines.len() == 1 {
cursor_offset = start_offset + lines[0].chars().count();
} else {
for line in lines.iter().skip(1) {
let mut next = Paragraph::new_empty_like(¶graphs[result_para]);
next.insert_text_at(0, line);
result_para += 1;
paragraphs.insert(result_para, next);
}
cursor_offset = lines.last().map(|line| line.chars().count()).unwrap_or(0);
}
paragraphs[result_para].merge_from(&suffix);
cursor_para = result_para;
}
let para_count = self
.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?
.len();
for hf_para_idx in 0..para_count {
self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
}
self.document.sections[section_idx].raw_stream = None;
self.rebuild_section(section_idx);
self.event_log
.push(DocumentEvent::HeaderFooterTextReplaced {
section: section_idx,
is_header,
apply_to,
start_para,
start_offset,
end_para,
end_offset,
inserted_end_para: cursor_para,
inserted_end_offset: cursor_offset,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"hfParaIndex\":{},\"charOffset\":{}",
cursor_para, cursor_offset
)))
}
#[allow(clippy::too_many_arguments)]
pub fn copy_selection_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
start_hf_para_idx: usize,
start_char_offset: usize,
end_hf_para_idx: usize,
end_char_offset: usize,
) -> Result<String, HwpError> {
if (start_hf_para_idx, start_char_offset) > (end_hf_para_idx, end_char_offset) {
return Err(HwpError::RenderError(
"시작 위치가 끝 위치보다 뒤에 있음".to_string(),
));
}
let mut clip_paragraphs = {
let paragraphs = self.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?;
if start_hf_para_idx >= paragraphs.len() || end_hf_para_idx >= paragraphs.len() {
return Err(HwpError::RenderError(format!(
"머리말/꼬리말 문단 범위 초과 (start={}, end={}, total={})",
start_hf_para_idx,
end_hf_para_idx,
paragraphs.len()
)));
}
let start_len = paragraphs[start_hf_para_idx].text.chars().count();
let end_len = paragraphs[end_hf_para_idx].text.chars().count();
if start_char_offset > start_len || end_char_offset > end_len {
return Err(HwpError::RenderError(
"머리말/꼬리말 문자 범위 초과".to_string(),
));
}
let mut selected = Vec::new();
if start_hf_para_idx == end_hf_para_idx {
selected.push(clip_paragraph_text_range_for_clipboard(
¶graphs[start_hf_para_idx],
start_char_offset,
end_char_offset,
));
} else {
selected.push(clip_paragraph_text_range_for_clipboard(
¶graphs[start_hf_para_idx],
start_char_offset,
start_len,
));
selected.extend(
paragraphs[(start_hf_para_idx + 1)..end_hf_para_idx]
.iter()
.cloned(),
);
selected.push(clip_paragraph_text_range_for_clipboard(
¶graphs[end_hf_para_idx],
0,
end_char_offset,
));
}
selected
};
for paragraph in &mut clip_paragraphs {
strip_structural_controls_for_text_clipboard(paragraph);
}
let plain_text = clip_paragraphs
.iter()
.map(|paragraph| paragraph.text.as_str())
.collect::<Vec<_>>()
.join("\n");
let escaped = super::super::helpers::json_escape(&plain_text);
self.clipboard = Some(ClipboardData {
paragraphs: clip_paragraphs,
plain_text,
copied_table_text_reflowed: false,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"text\":\"{}\"",
escaped
)))
}
pub fn get_char_properties_in_header_footer_native(
&self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
char_offset: usize,
) -> Result<String, HwpError> {
let paragraph = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
.ok_or_else(|| {
HwpError::RenderError("머리말/꼬리말 문단을 찾을 수 없음".to_string())
})?;
if char_offset > paragraph.text.chars().count() {
return Err(HwpError::RenderError(
"머리말/꼬리말 문자 범위 초과".to_string(),
));
}
Ok(self.build_char_properties_json(paragraph, char_offset))
}
#[allow(clippy::too_many_arguments)]
pub fn apply_char_format_in_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
start_hf_para_idx: usize,
start_char_offset: usize,
end_hf_para_idx: usize,
end_char_offset: usize,
props_json: &str,
) -> Result<String, HwpError> {
if (start_hf_para_idx, start_char_offset) > (end_hf_para_idx, end_char_offset) {
return Err(HwpError::RenderError(
"시작 위치가 끝 위치보다 뒤에 있음".to_string(),
));
}
{
let paragraphs = self.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?;
if start_hf_para_idx >= paragraphs.len() || end_hf_para_idx >= paragraphs.len() {
return Err(HwpError::RenderError(
"머리말/꼬리말 문단 범위 초과".to_string(),
));
}
if start_char_offset > paragraphs[start_hf_para_idx].text.chars().count()
|| end_char_offset > paragraphs[end_hf_para_idx].text.chars().count()
{
return Err(HwpError::RenderError(
"머리말/꼬리말 문자 범위 초과".to_string(),
));
}
}
let mut mods = parse_char_shape_mods(props_json);
if json_has_border_keys(props_json) {
mods.border_fill_id = Some(self.create_border_fill_from_json(props_json));
}
let affects_flow = char_shape_mods_affect_text_flow(&mods);
let mut changed_paragraphs = Vec::new();
for hf_para_idx in start_hf_para_idx..=end_hf_para_idx {
let paragraph_len = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
.map(|paragraph| paragraph.text.chars().count())
.unwrap_or(0);
let range_start = if hf_para_idx == start_hf_para_idx {
start_char_offset
} else {
0
};
let range_end = if hf_para_idx == end_hf_para_idx {
end_char_offset
} else {
paragraph_len
};
if range_end <= range_start {
continue;
}
let base_ids = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
.ok_or_else(|| {
HwpError::RenderError(format!("머리말/꼬리말 문단 {hf_para_idx} 누락"))
})?
.char_shape_ids_in_range(range_start, range_end);
let ids = self.document.modified_char_shape_ids(base_ids, &mods);
self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?
.try_map_char_shape_range(range_start, range_end, |id| {
ids.get(&id).copied().ok_or_else(|| {
HwpError::RenderError(format!("글자 모양 변환 ID {id} 누락"))
})
})?;
changed_paragraphs.push((hf_para_idx, range_start, range_end));
}
if affects_flow {
for (hf_para_idx, _, _) in &changed_paragraphs {
self.reflow_hf_paragraph(section_idx, is_header, apply_to, *hf_para_idx);
}
}
self.document.sections[section_idx].raw_stream = None;
self.rebuild_section(section_idx);
for (hf_para_idx, range_start, range_end) in changed_paragraphs {
self.event_log.push(DocumentEvent::CharFormatChanged {
section: section_idx,
para: hf_para_idx,
start: range_start,
end: range_end,
});
}
Ok("{\"ok\":true}".to_string())
}
pub fn delete_header_footer_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과 (총 {}개)",
section_idx,
self.document.sections.len()
)));
}
let apply = header_footer_apply_from_u8(apply_to);
let (pi, ci) = self
.find_header_footer_control(section_idx, is_header, apply)
.ok_or_else(|| {
let kind = if is_header { "머리말" } else { "꼬리말" };
HwpError::RenderError(format!(
"{}({})이 존재하지 않습니다",
kind,
apply_label(apply)
))
})?;
self.document.sections[section_idx].paragraphs[pi]
.controls
.remove(ci);
self.document.sections[section_idx].paragraphs[pi].char_count =
self.document.sections[section_idx].paragraphs[pi]
.char_count
.saturating_sub(8);
self.document.sections[section_idx].raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
Ok(format!("{{\"ok\":true}}"))
}
pub fn get_header_footer_list_native(
&self,
current_section_idx: usize,
current_is_header: bool,
current_apply_to: u8,
) -> Result<String, HwpError> {
let mut items = Vec::new();
let mut current_index: i32 = -1;
let current_apply = header_footer_apply_from_u8(current_apply_to);
for (si, section) in self.document.sections.iter().enumerate() {
for (pi, para) in section.paragraphs.iter().enumerate() {
for (ci, ctrl) in para.controls.iter().enumerate() {
let (is_header, apply) = match ctrl {
Control::Header(h) => (true, h.apply_to),
Control::Footer(f) => (false, f.apply_to),
_ => continue,
};
let kind = if is_header { "머리말" } else { "꼬리말" };
let label = apply_label(apply);
let at = header_footer_apply_to_u8(apply);
if si == current_section_idx
&& is_header == current_is_header
&& apply == current_apply
{
current_index = items.len() as i32;
}
items.push(format!(
"{{\"sectionIdx\":{},\"isHeader\":{},\"applyTo\":{},\"label\":\"{}({})\"}}",
si, is_header, at, kind, label
));
}
}
}
Ok(format!(
"{{\"ok\":true,\"items\":[{}],\"currentIndex\":{}}}",
items.join(","),
current_index
))
}
pub fn navigate_header_footer_by_page_native(
&self,
current_page: u32,
is_header: bool,
direction: i32, ) -> Result<String, HwpError> {
let total = self.page_count();
if total == 0 {
return Ok("{\"ok\":false}".to_string());
}
let current_ref = if let Ok((pc, _, _)) = self.find_page(current_page) {
if is_header {
pc.active_header.clone()
} else {
pc.active_footer.clone()
}
} else {
None
};
let mut page = current_page as i64 + direction as i64;
while page >= 0 && page < total as i64 {
let p = page as u32;
if let Ok((pc, _, _)) = self.find_page(p) {
let hf_ref = if is_header {
&pc.active_header
} else {
&pc.active_footer
};
if let Some(hf) = hf_ref {
let is_different_control = match ¤t_ref {
Some(cr) => {
cr.para_index != hf.para_index
|| cr.control_index != hf.control_index
|| cr.source_section_index != hf.source_section_index
}
None => true,
};
let section_idx = hf.source_section_index;
let para_idx = hf.para_index;
let ctrl_idx = hf.control_index;
let apply_to = if let Some(section) = self.document.sections.get(section_idx) {
if let Some(para) = section.paragraphs.get(para_idx) {
if let Some(ctrl) = para.controls.get(ctrl_idx) {
match ctrl {
Control::Header(h) => header_footer_apply_to_u8(h.apply_to),
Control::Footer(f) => header_footer_apply_to_u8(f.apply_to),
_ => 0,
}
} else {
0
}
} else {
0
}
} else {
0
};
return Ok(format!(
"{{\"ok\":true,\"pageIndex\":{},\"sectionIdx\":{},\"isHeader\":{},\"applyTo\":{}}}",
p, section_idx, is_header, apply_to
));
}
}
page += direction as i64;
}
Ok("{\"ok\":false}".to_string())
}
pub fn toggle_hide_header_footer_native(
&mut self,
page_num: u32,
is_header: bool,
) -> Result<String, HwpError> {
let total = self.page_count();
if page_num >= total {
return Err(HwpError::RenderError(format!(
"페이지 인덱스 {} 범위 초과 (총 {}개)",
page_num, total
)));
}
let key = (page_num, is_header);
let hidden = if self.hidden_header_footer.contains(&key) {
self.hidden_header_footer.remove(&key);
false
} else {
self.hidden_header_footer.insert(key);
true
};
self.invalidate_page_tree_cache_page(page_num);
Ok(format!("{{\"ok\":true,\"hidden\":{}}}", hidden))
}
pub(crate) fn reflow_hf_paragraph(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
) {
use crate::renderer::hwpunit_to_px;
let available_width = {
let section = &self.document.sections[section_idx];
let page_def = §ion.section_def.page_def;
let text_width =
page_def.width as i32 - page_def.margin_left as i32 - page_def.margin_right as i32;
hwpunit_to_px(text_width, self.dpi)
};
let styles = self.resolve_render_styles();
let para_shape_id =
match self.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx) {
Some(p) => p.para_shape_id,
None => return,
};
let para_style = styles.para_styles.get(para_shape_id as usize);
let margin_left = para_style.map(|s| s.margin_left).unwrap_or(0.0);
let margin_right = para_style.map(|s| s.margin_right).unwrap_or(0.0);
let final_width = (available_width - margin_left - margin_right).max(0.0);
let apply = header_footer_apply_from_u8(apply_to);
if let Some((pi, ci)) = self.find_header_footer_control(section_idx, is_header, apply) {
let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
let paragraphs = match ctrl {
Control::Header(h) => &mut h.paragraphs,
Control::Footer(f) => &mut f.paragraphs,
_ => return,
};
if let Some(para) = paragraphs.get_mut(hf_para_idx) {
reflow_line_segs(
para,
ParagraphBox::content_width_px(final_width, self.dpi),
&styles,
self.dpi,
);
}
}
}
pub fn get_para_properties_in_hf_native(
&self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
) -> Result<String, HwpError> {
let para = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
.ok_or_else(|| {
HwpError::RenderError("머리말/꼬리말 문단을 찾을 수 없음".to_string())
})?;
Ok(self.build_para_properties_json(para.para_shape_id, section_idx))
}
pub fn apply_para_format_in_hf_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
props_json: &str,
) -> Result<String, HwpError> {
let base_id = {
let para = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
.ok_or_else(|| {
HwpError::RenderError("머리말/꼬리말 문단을 찾을 수 없음".to_string())
})?;
para.para_shape_id
};
let mut mods = parse_para_shape_mods(props_json);
if json_has_tab_keys(props_json) {
let base_tab_def_id = self
.document
.doc_info
.para_shapes
.get(base_id as usize)
.map(|ps| ps.tab_def_id)
.unwrap_or(0);
let new_td = build_tab_def_from_json(
props_json,
base_tab_def_id,
&self.document.doc_info.tab_defs,
);
let new_tab_id = self.document.find_or_create_tab_def(new_td);
mods.tab_def_id = Some(new_tab_id);
}
if json_has_border_keys(props_json) {
let bf_id = self.create_border_fill_from_json(props_json);
mods.border_fill_id = Some(bf_id);
}
if let Some(arr) = parse_json_i16_array(props_json, "borderSpacing", 4) {
mods.border_spacing = Some([arr[0], arr[1], arr[2], arr[3]]);
}
let new_id = self.document.find_or_create_para_shape(base_id, &mods);
let (old_indent, new_indent) = self.para_shape_indents(base_id, new_id);
{
let para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
para.para_shape_id = new_id;
restamp_indentation(&mut para.line_segs, old_indent, new_indent);
}
if para_shape_mods_affect_text_flow(&mods) {
self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
}
self.document.sections[section_idx].raw_stream = None;
self.rebuild_section(section_idx);
self.event_log.push(DocumentEvent::ParaFormatChanged {
section: section_idx,
para: 0,
});
Ok("{\"ok\":true}".to_string())
}
pub fn insert_field_in_hf_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
hf_para_idx: usize,
char_offset: usize,
field_type: u8,
) -> Result<String, HwpError> {
let marker = match field_type {
1 => "\u{0015}", 2 => "\u{0016}", 3 => "\u{0017}", _ => {
return Err(HwpError::RenderError(format!(
"알 수 없는 필드 타입: {}",
field_type
)))
}
};
let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
let inserted_at = hf_para.insert_text_at(char_offset, marker);
self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
self.document.sections[section_idx].raw_stream = None;
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
let new_offset = inserted_at + 1;
self.event_log
.push(DocumentEvent::HeaderFooterTextReplaced {
section: section_idx,
is_header,
apply_to,
start_para: hf_para_idx,
start_offset: inserted_at,
end_para: hf_para_idx,
end_offset: inserted_at,
inserted_end_para: hf_para_idx,
inserted_end_offset: new_offset,
});
Ok(super::super::helpers::json_ok_with(&format!(
"\"charOffset\":{},\"insertedAt\":{},\"insertedLength\":1",
new_offset, inserted_at
)))
}
pub fn apply_hf_template_native(
&mut self,
section_idx: usize,
is_header: bool,
apply_to: u8,
template_id: u8,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과",
section_idx
)));
}
if template_id > 10 {
return Err(HwpError::RenderError(format!(
"알 수 없는 템플릿 ID: {}",
template_id
)));
}
let apply = header_footer_apply_from_u8(apply_to);
if self
.find_header_footer_control(section_idx, is_header, apply)
.is_some()
{
self.delete_header_footer_native(section_idx, is_header, apply_to)?;
}
self.create_header_footer_native(section_idx, is_header, apply_to)?;
if template_id == 0 {
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
return Ok("{\"ok\":true}".to_string());
}
let layout = if template_id <= 5 {
template_id
} else {
template_id - 5
};
let styled = template_id > 5;
let text = match layout {
1 => "\u{0015}".to_string(), 2 => "\u{0015}".to_string(), 3 => "\u{0015}".to_string(), 4 => "\u{0015}\t\u{0017}".to_string(), 5 => "\u{0017}\t\u{0015}".to_string(), _ => String::new(),
};
use crate::model::style::{
Alignment, CharShapeMods, ParaShapeMods, TabDef, TabItem, UnderlineType,
};
let alignment = match layout {
1 => Alignment::Left,
2 => Alignment::Center,
3 => Alignment::Right,
4 | 5 => Alignment::Left, _ => Alignment::Left,
};
{
let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, 0)?;
hf_para.insert_text_at(0, &text);
}
let base_para_id = {
let para = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, 0)
.unwrap();
para.para_shape_id
};
let mut para_mods = ParaShapeMods::default();
para_mods.alignment = Some(alignment);
if layout == 4 || layout == 5 {
let section = &self.document.sections[section_idx];
let page_def = §ion.section_def.page_def;
let text_width =
page_def.width as i32 - page_def.margin_left as i32 - page_def.margin_right as i32;
let new_td = TabDef {
raw_data: None,
attr: 0,
tabs: vec![TabItem {
position: text_width as u32,
tab_type: 1, fill_type: 0,
}],
auto_tab_left: false,
auto_tab_right: false,
};
let tab_id = self.document.find_or_create_tab_def(new_td);
para_mods.tab_def_id = Some(tab_id);
}
let new_para_id = self
.document
.find_or_create_para_shape(base_para_id, ¶_mods);
{
let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, 0)?;
hf_para.para_shape_id = new_para_id;
}
if styled {
let base_char_id = {
let para = self
.get_hf_paragraph_ref(section_idx, is_header, apply_to, 0)
.unwrap();
para.char_shapes
.first()
.map(|cs| cs.char_shape_id)
.unwrap_or(0)
};
let mut char_mods = CharShapeMods::default();
char_mods.bold = Some(true);
char_mods.underline_type = Some(UnderlineType::Bottom);
let new_char_id = self
.document
.find_or_create_char_shape(base_char_id, &char_mods);
self.get_hf_paragraph_mut(section_idx, is_header, apply_to, 0)?
.set_single_char_shape(new_char_id);
}
self.reflow_hf_paragraph(section_idx, is_header, apply_to, 0);
self.document.sections[section_idx].raw_stream = None;
self.rebuild_section(section_idx);
Ok("{\"ok\":true}".to_string())
}
}
fn is_hf_field_marker(ch: char) -> bool {
matches!(ch, '\u{0015}'..='\u{0017}')
}
pub(crate) fn has_header_footer_field_markers(document: &crate::model::document::Document) -> bool {
document
.sections
.iter()
.flat_map(|section| section.paragraphs.iter())
.flat_map(|para| para.controls.iter())
.flat_map(|ctrl| match ctrl {
Control::Header(header) => header.paragraphs.as_slice(),
Control::Footer(footer) => footer.paragraphs.as_slice(),
_ => &[],
})
.any(|para| para.text.chars().any(is_hf_field_marker))
}
pub(crate) fn lower_header_footer_field_markers(
document: &mut crate::model::document::Document,
file_name: &str,
hwpx: bool,
) {
if !has_header_footer_field_markers(document) {
return;
}
let mut max_field_id = 0;
for para in document
.sections
.iter()
.flat_map(|section| section.paragraphs.iter())
{
crate::document_core::queries::field_query::collect_max_field_id(para, &mut max_field_id);
}
let mut next_field_id = max_field_id.saturating_add(1);
let hf_paragraphs = document
.sections
.iter_mut()
.flat_map(|section| section.paragraphs.iter_mut())
.flat_map(|para| para.controls.iter_mut())
.flat_map(|ctrl| match ctrl {
Control::Header(header) => header.paragraphs.iter_mut(),
Control::Footer(footer) => footer.paragraphs.iter_mut(),
_ => Default::default(),
});
for para in hf_paragraphs {
let markers: Vec<(usize, char)> = para
.text
.chars()
.enumerate()
.filter(|(_, ch)| is_hf_field_marker(*ch))
.collect();
if markers.is_empty() {
continue;
}
let text_end = para
.char_offsets
.last()
.zip(para.text.chars().last())
.map_or(0, |(offset, ch)| offset + Paragraph::char_stream_len(ch));
if para.char_count.saturating_sub(text_end) % 8 == 0 {
para.char_count += 1;
}
for (idx, marker) in markers.into_iter().rev() {
let ctrl_idx = para
.control_text_positions()
.into_iter()
.filter(|pos| *pos <= idx)
.count();
for range in &mut para.field_ranges {
if range.control_idx >= ctrl_idx {
range.control_idx += 1;
}
}
let ctrl = if marker == '\u{0017}' {
let end = insert_field_text(para, idx, file_name);
para.field_ranges.push(crate::model::paragraph::FieldRange {
start_char_idx: idx,
end_char_idx: end,
control_idx: ctrl_idx,
..Default::default()
});
let field = path_field(next_field_id, hwpx);
next_field_id = next_field_id.saturating_add(1);
Control::Field(field)
} else {
insert_auto_number_placeholder(para, idx);
Control::AutoNumber(crate::model::control::AutoNumber {
number_type: if marker == '\u{0015}' {
crate::model::control::AutoNumberType::Page
} else {
crate::model::control::AutoNumberType::TotalPage
},
number: 1,
assigned_number: 1,
..Default::default()
})
};
para.align_ctrl_data_records();
para.controls.insert(ctrl_idx, ctrl);
para.ctrl_data_records.insert(ctrl_idx, None);
}
}
}
fn insert_auto_number_placeholder(para: &mut Paragraph, idx: usize) {
const EXTRA: u32 = 7;
let Some((byte, _)) = para.text.char_indices().nth(idx) else {
return;
};
para.text.replace_range(byte..byte + 1, " ");
let slot = para.char_offsets[idx];
for offset in &mut para.char_offsets[idx + 1..] {
*offset += EXTRA;
}
para.shift_position_metadata_for_stream_insertion(slot + 1, EXTRA);
para.char_count += EXTRA;
}
fn insert_field_text(para: &mut Paragraph, idx: usize, text: &str) -> usize {
let at = para.insert_text_at(idx, text);
let end = at + text.chars().count();
para.shift_for_control_slot_insert(end);
para.shift_for_control_slot_insert(at);
para.char_count += 16;
para.delete_text_at(end, 1);
end
}
fn path_field(field_id: u32, hwpx: bool) -> crate::model::control::Field {
use crate::model::control::{Field, FieldType, Parameter, ParameterList};
const COMMAND: &str = "$F";
let string_param = |name: &str| Parameter::String {
name: Some(name.to_string()),
value: COMMAND.to_string(),
preserve_space: false,
};
Field {
field_type: FieldType::Path,
command: COMMAND.to_string(),
field_id,
ctrl_id: crate::parser::tags::FIELD_PATH,
parameters: if hwpx {
ParameterList {
name: Some(String::new()),
items: vec![
Parameter::Integer {
name: Some("Prop".to_string()),
value: 8,
},
string_param("Command"),
string_param("Format"),
],
}
} else {
ParameterList::default()
},
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_test_core() -> DocumentCore {
use crate::model::document::{Document, Section, SectionDef};
use crate::model::page::PageDef;
let mut doc = Document::default();
let section = Section {
section_def: SectionDef {
page_def: PageDef {
width: 59528, height: 84188, margin_left: 8504,
margin_right: 8504,
margin_top: 5668,
margin_bottom: 4252,
margin_header: 4252,
margin_footer: 4252,
..Default::default()
},
..Default::default()
},
paragraphs: vec![Paragraph::default()],
trailing_lists: None,
raw_stream: None,
raw_provenance: None,
};
doc.sections.push(section);
let mut core = DocumentCore::new_empty();
core.document = doc;
core
}
#[test]
fn test_create_and_get_header() {
let mut core = make_test_core();
let result = core.get_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("\"exists\":false"));
let result = core.create_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("\"ok\":true"));
assert!(result.contains("\"kind\":\"header\""));
let result = core.get_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("\"exists\":true"));
assert!(result.contains("\"paraCount\":1"));
}
#[test]
fn test_create_and_get_footer() {
let mut core = make_test_core();
let result = core.create_header_footer_native(0, false, 0).unwrap();
assert!(result.contains("\"kind\":\"footer\""));
let result = core.get_header_footer_native(0, false, 0).unwrap();
assert!(result.contains("\"exists\":true"));
}
#[test]
fn test_duplicate_create_fails() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
let result = core.create_header_footer_native(0, true, 0);
assert!(result.is_err());
}
#[test]
fn test_insert_text_in_header() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
let result = core
.insert_text_in_header_footer_native(0, true, 0, 0, 0, "Hello")
.unwrap();
assert!(result.contains("\"charOffset\":5"));
let result = core.get_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("Hello"));
let info = core
.get_header_footer_para_info_native(0, true, 0, 0)
.unwrap();
let value: serde_json::Value = serde_json::from_str(&info).unwrap();
assert_eq!(value["charCount"], 5);
assert_eq!(value["text"], "Hello");
}
#[test]
fn field_insert_reports_where_the_marker_actually_landed() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.insert_field_in_hf_native(0, true, 0, 0, 0, 3)
.expect("file-name field");
let result = core
.insert_field_in_hf_native(0, true, 0, 0, 1, 1)
.expect("page-number field after the file-name marker");
assert!(result.contains("\"charOffset\":2"), "{result}");
assert!(result.contains("\"insertedAt\":1"), "{result}");
assert!(result.contains("\"insertedLength\":1"), "{result}");
let info = core
.get_header_footer_para_info_native(0, true, 0, 0)
.unwrap();
assert!(info.contains("\"charCount\":2"), "{info}");
}
#[test]
fn field_insert_reports_actual_offset_separately_from_cursor_offset() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
{
let para = core.get_hf_paragraph_mut(0, true, 0, 0).unwrap();
para.text = "A".to_string();
para.char_offsets = vec![0];
para.controls.push(Control::Footnote(Box::default()));
}
let result = core
.insert_field_in_hf_native(0, true, 0, 0, 2, 1)
.expect("field after trailing inline control");
assert!(result.contains("\"charOffset\":2"), "{result}");
assert!(result.contains("\"insertedAt\":1"), "{result}");
assert!(result.contains("\"insertedLength\":1"), "{result}");
core.delete_text_in_header_footer_native(0, true, 0, 0, 1, 1)
.expect("undo removes the marker at insertedAt");
let content = core.get_header_footer_native(0, true, 0).unwrap();
assert!(content.contains("\"text\":\"A\""), "{content}");
}
#[test]
fn test_delete_text_in_header() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "Hello World")
.unwrap();
let result = core
.delete_text_in_header_footer_native(0, true, 0, 0, 5, 6)
.unwrap();
assert!(result.contains("\"charOffset\":5"));
let result = core.get_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("Hello"));
}
#[test]
fn test_split_merge_paragraph_in_header() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "HelloWorld")
.unwrap();
let result = core
.split_paragraph_in_header_footer_native(0, true, 0, 0, 5, None)
.unwrap();
assert!(result.contains("\"hfParaIndex\":1"));
assert!(result.contains("\"charOffset\":0"));
let result = core
.get_header_footer_para_info_native(0, true, 0, 0)
.unwrap();
assert!(result.contains("\"paraCount\":2"));
let result = core
.merge_paragraph_in_header_footer_native(0, true, 0, 1)
.unwrap();
assert!(result.contains("\"hfParaIndex\":0"));
assert!(result.contains("\"charOffset\":5"));
let result = core
.get_header_footer_para_info_native(0, true, 0, 0)
.unwrap();
assert!(result.contains("\"paraCount\":1"));
}
#[test]
fn merge_paragraph_in_header_undo_restores_removed_paragraph_meta() {
use crate::document_core::helpers::removed_para_meta_of;
use crate::model::paragraph::NumberingRestart;
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "HelloWorld")
.unwrap();
core.split_paragraph_in_header_footer_native(0, true, 0, 0, 5, None)
.unwrap();
let second = core.get_hf_paragraph_mut(0, true, 0, 1).unwrap();
second.para_shape_id = 20;
second.style_id = 5;
second.numbering_restart = Some(NumberingRestart::ContinuePrevious);
second.raw_header_extra = vec![0, 0, 0, 0, 0, 0, 0xBB, 0xBB, 0xBB, 0xBB];
let merged = core
.merge_paragraph_in_header_footer_native(0, true, 0, 1)
.unwrap();
let meta = removed_para_meta_of(&merged);
core.split_paragraph_in_header_footer_native(0, true, 0, 0, 5, Some(meta))
.unwrap();
let restored = core.get_hf_paragraph_mut(0, true, 0, 1).unwrap();
assert_eq!(restored.text, "World");
assert_eq!(restored.para_shape_id, 20);
assert_eq!(restored.style_id, 5);
assert_eq!(
restored.numbering_restart,
Some(NumberingRestart::ContinuePrevious)
);
assert_eq!(
restored.raw_header_extra,
vec![0, 0, 0, 0, 0, 0, 0xBB, 0xBB, 0xBB, 0xBB]
);
}
#[test]
fn test_delete_header_footer() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "머리말 텍스트")
.unwrap();
let result = core.delete_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("\"ok\":true"));
let result = core.get_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("\"exists\":false"));
}
#[test]
fn test_delete_nonexistent_fails() {
let mut core = make_test_core();
let result = core.delete_header_footer_native(0, true, 0);
assert!(result.is_err());
}
#[test]
fn test_get_header_footer_list() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.create_header_footer_native(0, false, 0).unwrap();
let result = core.get_header_footer_list_native(0, true, 0).unwrap();
assert!(result.contains("\"currentIndex\":0"));
assert!(result.contains("머리말(양 쪽)"));
assert!(result.contains("꼬리말(양 쪽)"));
let result = core.get_header_footer_list_native(0, false, 0).unwrap();
assert!(result.contains("\"currentIndex\":1"));
}
#[test]
fn test_odd_even_header() {
let mut core = make_test_core();
core.create_header_footer_native(0, true, 0).unwrap();
core.create_header_footer_native(0, true, 2).unwrap();
let result = core.get_header_footer_native(0, true, 0).unwrap();
assert!(result.contains("\"exists\":true"));
assert!(result.contains("양 쪽"));
let result = core.get_header_footer_native(0, true, 2).unwrap();
assert!(result.contains("\"exists\":true"));
assert!(result.contains("홀수 쪽"));
let result = core.get_header_footer_native(0, true, 1).unwrap();
assert!(result.contains("\"exists\":false"));
}
#[test]
#[ignore] fn test_p222_header_structure() {
let data = std::fs::read("samples/p222.hwp").expect("samples/p222.hwp 파일 읽기 실패");
let mut core = DocumentCore::from_bytes(&data).expect("문서 로드 실패");
let num_sections = core.document.sections.len();
eprintln!("=== p222.hwp 머리말 구조 진단 ===");
eprintln!("구역 수: {}", num_sections);
eprintln!("전체 페이지 수: {}", core.page_count());
for si in 0..num_sections {
let section = &core.document.sections[si];
eprintln!(
"\n--- 구역 {} (문단 {}개) ---",
si,
section.paragraphs.len()
);
for (pi, para) in section.paragraphs.iter().enumerate() {
for (ci, ctrl) in para.controls.iter().enumerate() {
match ctrl {
Control::Header(h) => {
eprintln!(
" 머리말: para[{}].ctrl[{}] apply_to={:?} 문단수={} 텍스트=[{}]",
pi,
ci,
h.apply_to,
h.paragraphs.len(),
h.paragraphs
.iter()
.map(|p| p.text.clone())
.collect::<Vec<_>>()
.join("|")
);
}
Control::Footer(f) => {
eprintln!(
" 꼬리말: para[{}].ctrl[{}] apply_to={:?} 문단수={} 텍스트=[{}]",
pi,
ci,
f.apply_to,
f.paragraphs.len(),
f.paragraphs
.iter()
.map(|p| p.text.clone())
.collect::<Vec<_>>()
.join("|")
);
}
_ => {}
}
}
}
}
eprintln!("\n--- 페이지별 active header/footer ---");
for page_num in 0..core.page_count() {
if let Ok((pc, _, _)) = core.find_page(page_num) {
let hdr = if let Some(ref h) = pc.active_header {
format!(
"sec={} para={} ctrl={}",
h.source_section_index, h.para_index, h.control_index
)
} else {
"없음".to_string()
};
let ftr = if let Some(ref f) = pc.active_footer {
format!(
"sec={} para={} ctrl={}",
f.source_section_index, f.para_index, f.control_index
)
} else {
"없음".to_string()
};
eprintln!(" 페이지 {}: header=[{}] footer=[{}]", page_num, hdr, ftr);
}
}
for apply_to_val in [0u8, 1, 2] {
for sec_idx in 0..num_sections {
let result = core
.get_header_footer_native(sec_idx, true, apply_to_val)
.unwrap();
if result.contains("\"exists\":true") {
eprintln!(
" get_header_footer(sec={}, is_header=true, apply_to={}) => {}",
sec_idx, apply_to_val, result
);
}
}
}
eprintln!("\n--- hitTestHeaderFooter + 텍스트 삽입 시뮬레이션 ---");
for page in [6u32, 7] {
let hf_hit = core.hit_test_header_footer_native(page, 100.0, 20.0);
eprintln!(
" 페이지 {} hitTestHeaderFooter(100,20) => {:?}",
page, hf_hit
);
let hf_hit2 = core.hit_test_header_footer_native(page, 200.0, 50.0);
eprintln!(
" 페이지 {} hitTestHeaderFooter(200,50) => {:?}",
page, hf_hit2
);
}
eprintln!("\n--- active_header apply_to 직접 확인 ---");
for page in [6u32, 7] {
if let Ok((pc, _, _)) = core.find_page(page) {
if let Some(ref hdr) = pc.active_header {
let sec = hdr.source_section_index;
let pi = hdr.para_index;
let ci = hdr.control_index;
if let Some(section) = core.document.sections.get(sec) {
if let Some(para) = section.paragraphs.get(pi) {
if let Some(ctrl) = para.controls.get(ci) {
let apply_to = match ctrl {
Control::Header(h) => header_footer_apply_to_u8(h.apply_to),
Control::Footer(f) => header_footer_apply_to_u8(f.apply_to),
_ => 255,
};
eprintln!(
" 페이지 {} → sec={}, para={}, ctrl={}, apply_to={}",
page, sec, pi, ci, apply_to
);
let result = core.insert_text_in_header_footer_native(
sec, true, apply_to, 0, 0, "T",
);
eprintln!(" insert_text => {:?}", result);
}
}
}
} else {
eprintln!(" 페이지 {} → active_header 없음", page);
}
}
}
eprintln!("\n--- 텍스트 삽입 테스트 ---");
for apply_to_val in [0u8, 1, 2] {
for sec_idx in 0..num_sections {
let result = core.insert_text_in_header_footer_native(
sec_idx,
true,
apply_to_val,
0,
0,
"X",
);
match result {
Ok(r) => eprintln!(
" insert(sec={}, apply_to={}) => OK: {}",
sec_idx, apply_to_val, r
),
Err(e) => eprintln!(
" insert(sec={}, apply_to={}) => ERR: {}",
sec_idx, apply_to_val, e
),
}
}
}
}
#[test]
fn test_body_text_after_hf_template() {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().unwrap();
let controls_before = core.document.sections[0].paragraphs[0].controls.len();
core.apply_hf_template_native(0, false, 0, 2).unwrap();
let para = &core.document.sections[0].paragraphs[0];
assert_eq!(para.controls.len(), controls_before + 1);
assert!(
para.char_count >= (para.controls.len() as u32) * 8,
"char_count({})가 컨트롤 UTF-16 크기({})보다 작음",
para.char_count,
para.controls.len() * 8
);
core.insert_text_native(0, 0, 0, "가나다").unwrap();
let all_text: String = core.composed[0][0]
.lines
.iter()
.flat_map(|l| l.runs.iter().map(|r| r.text.as_str()))
.collect();
assert!(
all_text.contains("가나다"),
"HF 컨트롤 추가 후 본문 텍스트가 composed에 누락됨: {:?}",
all_text
);
let tree = core.build_page_tree(0).unwrap();
assert!(
format!("{:?}", tree).contains("가나다"),
"렌더 트리에 본문 텍스트 없음"
);
}
#[test]
fn issue3214_header_creation_keeps_ctrl_data_records_aligned() {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().unwrap();
core.insert_text_native(0, 0, 0, "ab").unwrap();
core.create_header_footer_native(0, true, 0).unwrap();
let para = &core.document.sections[0].paragraphs[0];
assert_eq!(
para.controls.len(),
para.ctrl_data_records.len(),
"머리말 생성 후 controls/ctrl_data_records 길이가 어긋났다"
);
core.insert_footnote_native(0, 0, 2).unwrap();
let para = &core.document.sections[0].paragraphs[0];
assert_eq!(para.controls.len(), para.ctrl_data_records.len());
}
#[test]
fn issue3214_insert_survives_unaligned_ctrl_data_records() {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().unwrap();
core.insert_text_native(0, 0, 0, "ab").unwrap();
core.create_header_footer_native(0, true, 0).unwrap();
{
let para = &mut core.document.sections[0].paragraphs[0];
para.ctrl_data_records.clear();
assert!(!para.controls.is_empty());
}
core.insert_footnote_native(0, 0, 2).unwrap();
let para = &core.document.sections[0].paragraphs[0];
assert_eq!(
para.controls.len(),
para.ctrl_data_records.len(),
"삽입 후 두 배열 길이가 정합해야 한다"
);
}
#[test]
fn para_format_margin_change_in_header_reflows_with_correct_width_not_stale_styles() {
use crate::model::document::{Document, Section, SectionDef};
use crate::model::page::PageDef;
use crate::model::paragraph::CharShapeRef;
let mut doc = Document::default();
let section = Section {
section_def: SectionDef {
page_def: PageDef {
width: 28504,
height: 84188,
margin_left: 4252,
margin_right: 4252,
margin_top: 5668,
margin_bottom: 4252,
margin_header: 4252,
margin_footer: 4252,
..Default::default()
},
..Default::default()
},
paragraphs: vec![Paragraph::default()],
trailing_lists: None,
raw_stream: None,
raw_provenance: None,
};
doc.sections.push(section);
let mut core = DocumentCore::new_empty();
core.document = doc;
core.composed = vec![Vec::new()];
core.dirty_sections = vec![true];
core.dirty_paragraphs = vec![None];
core.create_header_footer_native(0, true, 0)
.expect("머리말 생성이 성공해야 함");
let text = "A".repeat(200);
{
let para = core.get_hf_paragraph_mut(0, true, 0, 0).unwrap();
para.text = text.clone();
para.char_offsets = (0..text.chars().count() as u32).collect();
para.char_count = text.chars().count() as u32 + 1;
para.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}];
para.has_para_text = true;
}
core.rebuild_section(0);
core.reflow_hf_paragraph(0, true, 0, 0);
let before_lines = core
.get_hf_paragraph_ref(0, true, 0, 0)
.unwrap()
.line_segs
.len();
core.apply_para_format_in_hf_native(0, true, 0, 0, r#"{"marginLeft":8000}"#)
.expect("서식 적용이 성공해야 함");
let after_lines = core
.get_hf_paragraph_ref(0, true, 0, 0)
.unwrap()
.line_segs
.len();
assert!(
after_lines > before_lines,
"marginLeft 적용으로 사용 가능 폭이 줄었으면 줄 수가 늘어야 함 \
(before={before_lines}줄, after={after_lines}줄 — self.styles가 stale이면 \
새 para_shape_id 조회가 None이 되어 margin=0으로 폴백, after==before로 남는다)"
);
}
}