use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::{Control, Field, FieldType};
use crate::model::event::DocumentEvent;
use crate::model::paragraph::{FieldRange, Paragraph};
use crate::parser::tags;
#[derive(Debug, Clone)]
pub struct FieldLocation {
pub section_index: usize,
pub para_index: usize,
pub nested_path: Vec<NestedEntry>,
}
#[derive(Debug, Clone)]
pub enum NestedEntry {
TableCell {
control_index: usize,
cell_index: usize,
para_index: usize,
},
TextBox {
control_index: usize,
para_index: usize,
},
}
#[derive(Debug)]
pub struct FieldInfo {
pub field: Field,
pub location: FieldLocation,
pub value: String,
pub field_range_index: usize,
pub list_id: u32,
pub para_in_list: usize,
pub start_pos: usize,
pub end_pos: usize,
}
pub const ROOT_LIST_ID: u32 = 0;
pub const FIRST_SUB_LIST_ID: u32 = 2;
#[derive(Debug, Clone)]
pub struct ListEntry {
pub list_id: u32,
pub is_cell: bool,
pub host_list_id: u32,
pub section_index: usize,
pub host_para_index: usize,
pub control_index: usize,
pub cell_index: usize,
pub para_count: usize,
pub grid: Option<CellGrid>,
}
#[derive(Debug, Clone, Copy)]
pub struct CellGrid {
pub row: u16,
pub col: u16,
pub row_span: u16,
pub col_span: u16,
pub cell_count: usize,
}
struct ListWalk {
next_id: u32,
lists: Vec<ListEntry>,
}
impl ListWalk {
fn new() -> Self {
Self {
next_id: FIRST_SUB_LIST_ID,
lists: Vec::new(),
}
}
fn alloc(&mut self) -> u32 {
let id = self.next_id;
self.next_id += 1;
id
}
}
impl DocumentCore {
pub fn collect_all_fields(&self) -> Vec<FieldInfo> {
self.collect_fields_and_lists().0
}
pub fn collect_fields_and_lists(&self) -> (Vec<FieldInfo>, Vec<ListEntry>) {
let mut result = Vec::new();
let mut walk = ListWalk::new();
let mut para_base = 0;
for (si, sec) in self.document.sections.iter().enumerate() {
for (pi, para) in sec.paragraphs.iter().enumerate() {
let loc = FieldLocation {
section_index: si,
para_index: pi,
nested_path: Vec::new(),
};
collect_fields_from_paragraph(
para,
&loc,
ROOT_LIST_ID,
para_base + pi,
&mut walk,
&mut result,
);
}
para_base += sec.paragraphs.len();
}
(result, walk.lists)
}
pub fn insert_click_here_field_at(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
guide: &str,
memo: &str,
name: &str,
editable: bool,
) -> Result<String, HwpError> {
let field_id = self.next_click_here_field_id();
let inserted_offset = {
let section = self
.document
.sections
.get_mut(section_idx)
.ok_or_else(|| HwpError::InvalidField("구역 인덱스 초과".into()))?;
section.raw_stream = None;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField("문단 인덱스 초과".into()))?;
insert_click_here_field_in_para(
para,
char_offset,
field_id,
guide,
memo,
name,
editable,
)?
};
let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
&self.document.sections[section_idx].paragraphs[para_idx],
);
self.reflow_paragraph(section_idx, para_idx);
let doc_hwp3_layout = self.document.layout_profile().hwp3_layout();
crate::renderer::composer::recalculate_section_vpos(
&mut self.document.sections[section_idx].paragraphs,
para_idx,
None,
stored_end_for_reset,
&self.styles,
self.dpi,
doc_hwp3_layout,
);
self.recompose_paragraph(section_idx, para_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
self.event_log.push(DocumentEvent::TextInserted {
section: section_idx,
para: para_idx,
offset: inserted_offset,
len: 0,
});
Ok(format!(
"{{\"ok\":true,\"fieldId\":{},\"charOffset\":{}}}",
field_id, inserted_offset
))
}
pub fn insert_click_here_field_at_in_cell(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: usize,
cell_para_idx: usize,
char_offset: usize,
_is_textbox: bool,
guide: &str,
memo: &str,
name: &str,
editable: bool,
) -> Result<String, HwpError> {
let field_id = self.next_click_here_field_id();
let inserted_offset = {
let para = self.get_cell_paragraph_mut(
section_idx,
parent_para_idx,
control_idx,
cell_idx,
cell_para_idx,
)?;
insert_click_here_field_in_para(
para,
char_offset,
field_id,
guide,
memo,
name,
editable,
)?
};
self.mark_cell_control_dirty(section_idx, parent_para_idx, control_idx);
self.reflow_cell_paragraph(
section_idx,
parent_para_idx,
control_idx,
cell_idx,
cell_para_idx,
);
if let Some(section) = self.document.sections.get_mut(section_idx) {
section.raw_stream = None;
}
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
self.event_log.push(DocumentEvent::CellTextChanged {
section: section_idx,
para: parent_para_idx,
ctrl: control_idx,
cell: cell_idx,
});
Ok(format!(
"{{\"ok\":true,\"fieldId\":{},\"charOffset\":{}}}",
field_id, inserted_offset
))
}
pub fn insert_click_here_field_at_by_path(
&mut self,
section_idx: usize,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
char_offset: usize,
guide: &str,
memo: &str,
name: &str,
editable: bool,
) -> Result<String, HwpError> {
if path.is_empty() {
return Err(HwpError::InvalidField("cellPath가 비어 있음".into()));
}
let field_id = self.next_click_here_field_id();
let inserted_offset = {
let para = self.get_cell_paragraph_mut_by_path(section_idx, parent_para_idx, path)?;
insert_click_here_field_in_para(
para,
char_offset,
field_id,
guide,
memo,
name,
editable,
)?
};
let outer_ctrl = path[0].0;
let inner_para = path.last().map(|entry| entry.2).unwrap_or(0);
self.reflow_cell_paragraph_by_path(section_idx, parent_para_idx, path, inner_para);
self.recalculate_cell_paragraph_vpos_by_path(
section_idx,
parent_para_idx,
path,
inner_para,
None,
);
self.mark_cell_control_dirty(section_idx, parent_para_idx, outer_ctrl);
if let Some(section) = self.document.sections.get_mut(section_idx) {
section.raw_stream = None;
}
self.mark_section_dirty(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
self.event_log.push(DocumentEvent::CellTextChanged {
section: section_idx,
para: parent_para_idx,
ctrl: outer_ctrl,
cell: path[0].1,
});
Ok(format!(
"{{\"ok\":true,\"fieldId\":{},\"charOffset\":{}}}",
field_id, inserted_offset
))
}
pub fn get_field_list_json(&self) -> String {
let fields = self.collect_all_fields();
let entries: Vec<String> = fields
.iter()
.map(|fi| {
let name = fi.field.field_name().unwrap_or("");
let guide = fi.field.guide_text().unwrap_or("");
let location_json = field_location_json(&fi.location);
let (start_char_idx, end_char_idx) = field_range_bounds(self, fi)
.unwrap_or((0, fi.value.chars().count()));
format!(
"{{\"fieldId\":{},\"fieldType\":\"{}\",\"cellField\":{},\"name\":{},\"guide\":{},\"command\":{},\"value\":{},\"location\":{},\"startCharIdx\":{},\"endCharIdx\":{},\"editableInForm\":{},\"listId\":{},\"paraInList\":{},\"startPos\":{},\"endPos\":{}}}",
fi.field.field_id,
fi.field.field_type_str(),
fi.field.ctrl_id == 0,
json_escape(name),
json_escape(guide),
json_escape(&fi.field.command),
json_escape(&fi.value),
location_json,
start_char_idx,
end_char_idx,
fi.field.is_editable_in_form(),
fi.list_id,
fi.para_in_list,
fi.start_pos,
fi.end_pos,
)
})
.collect();
format!("[{}]", entries.join(","))
}
pub fn is_empty_document(&self) -> bool {
self.document.sections.iter().all(|section| {
section.paragraphs.iter().all(|para| {
para.text.is_empty()
&& para
.controls
.iter()
.all(|ctrl| matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)))
})
})
}
pub fn get_cursor_model_json(&self) -> String {
let (_, lists) = self.collect_fields_and_lists();
let entries: Vec<String> = lists
.iter()
.map(|l| {
let grid = match l.grid {
Some(g) => format!(
",\"row\":{},\"col\":{},\"rowSpan\":{},\"colSpan\":{},\"cellCount\":{}",
g.row, g.col, g.row_span, g.col_span, g.cell_count,
),
None => String::new(),
};
format!(
"{{\"listId\":{},\"isCell\":{},\"hostListId\":{},\"sectionIndex\":{},\"hostPara\":{},\"controlIndex\":{},\"cellIndex\":{},\"paraCount\":{}{}}}",
l.list_id,
l.is_cell,
l.host_list_id,
l.section_index,
l.host_para_index,
l.control_index,
l.cell_index,
l.para_count,
grid,
)
})
.collect();
let para_count = root_para_count(self);
let top_pos = self
.document
.sections
.first()
.and_then(|s| s.paragraphs.first())
.map(leading_anchor_pos)
.unwrap_or(0);
let end_para = para_count.saturating_sub(1);
let end_pos = root_para_location(self, end_para)
.and_then(|(si, pi)| self.document.sections.get(si)?.paragraphs.get(pi))
.map(|p| (p.char_count as usize).saturating_sub(1))
.unwrap_or(0);
format!(
"{{\"listCount\":{},\"root\":{{\"paraCount\":{},\"topPos\":{},\"endPara\":{},\"endPos\":{}}},\"lists\":[{}]}}",
FIRST_SUB_LIST_ID as usize + lists.len(),
para_count,
top_pos,
end_para,
end_pos,
entries.join(","),
)
}
pub fn get_field_value_by_id(&self, field_id: u32) -> Result<String, HwpError> {
let fields = self.collect_all_fields();
for fi in &fields {
if fi.field.field_id == field_id {
return Ok(format!(
"{{\"ok\":true,\"value\":{}}}",
json_escape(&fi.value)
));
}
}
Err(HwpError::InvalidField(format!("필드 ID {} 없음", field_id)))
}
pub fn get_field_value_by_name(&self, name: &str) -> Result<String, HwpError> {
let fields = self.collect_all_fields();
for fi in &fields {
if let Some(field_name) = fi.field.field_name() {
if field_name == name {
return Ok(format!(
"{{\"ok\":true,\"fieldId\":{},\"value\":{}}}",
fi.field.field_id,
json_escape(&fi.value),
));
}
}
}
Err(HwpError::InvalidField(format!("필드 이름 '{}' 없음", name)))
}
pub fn set_field_value_by_id(
&mut self,
field_id: u32,
value: &str,
) -> Result<String, HwpError> {
let fields = self.collect_all_fields();
let fi = fields
.iter()
.find(|f| f.field.field_id == field_id)
.ok_or_else(|| HwpError::InvalidField(format!("필드 ID {} 없음", field_id)))?;
let location = fi.location.clone();
let fri = fi.field_range_index;
let old_value = fi.value.clone();
let is_cell_field = fi.field.ctrl_id == 0;
let section_index = location.section_index;
let stored_end_for_reset = self.field_body_flow_end(&location);
self.validate_field_reflow_location(&location)?;
if is_cell_field {
self.set_cell_field_text(&location, value)?;
} else {
self.set_field_text_at(&location, fri, value)?;
}
self.reflow_field_location_after_edit(&location, stored_end_for_reset)?;
if let Some(sec) = self.document.sections.get_mut(section_index) {
sec.raw_stream = None;
}
self.recompose_section(section_index);
Ok(format!(
"{{\"ok\":true,\"fieldId\":{},\"oldValue\":{},\"newValue\":{}}}",
field_id,
json_escape(&old_value),
json_escape(value),
))
}
pub fn set_field_value_by_name(&mut self, name: &str, value: &str) -> Result<String, HwpError> {
self.set_field_value_by_name_at(name, 0, value)
}
pub fn set_field_value_by_name_at(
&mut self,
name: &str,
occurrence: usize,
value: &str,
) -> Result<String, HwpError> {
let fields = self.collect_all_fields();
let fi = fields
.iter()
.filter(|f| f.field.field_name().map(|n| n == name).unwrap_or(false))
.nth(occurrence)
.ok_or_else(|| {
HwpError::InvalidField(format!("필드 이름 '{}'[{}] 없음", name, occurrence))
})?;
let field_id = fi.field.field_id;
let location = fi.location.clone();
let fri = fi.field_range_index;
let old_value = fi.value.clone();
let is_cell_field = fi.field.ctrl_id == 0;
let section_index = location.section_index;
let stored_end_for_reset = self.field_body_flow_end(&location);
self.validate_field_reflow_location(&location)?;
if is_cell_field {
self.set_cell_field_text(&location, value)?;
} else {
self.set_field_text_at(&location, fri, value)?;
}
self.reflow_field_location_after_edit(&location, stored_end_for_reset)?;
if let Some(sec) = self.document.sections.get_mut(section_index) {
sec.raw_stream = None;
}
self.recompose_section(section_index);
Ok(format!(
"{{\"ok\":true,\"fieldId\":{},\"oldValue\":{},\"newValue\":{}}}",
field_id,
json_escape(&old_value),
json_escape(value),
))
}
fn field_body_flow_end(&self, location: &FieldLocation) -> Option<i32> {
if !location.nested_path.is_empty() {
return None;
}
self.document
.sections
.get(location.section_index)
.and_then(|section| section.paragraphs.get(location.para_index))
.and_then(crate::renderer::composer::paragraph_flow_end)
}
fn field_nested_reflow_path(
location: &FieldLocation,
) -> Result<Vec<(usize, usize, usize)>, HwpError> {
if location.nested_path.is_empty() {
return Err(HwpError::InvalidField(
"중첩 필드 위치에 소유자 경로 없음".into(),
));
}
Ok(location
.nested_path
.iter()
.map(|entry| match entry {
NestedEntry::TableCell {
control_index,
cell_index,
para_index,
} => (*control_index, *cell_index, *para_index),
NestedEntry::TextBox {
control_index,
para_index,
} => (*control_index, 0, *para_index),
})
.collect())
}
fn validate_field_reflow_location(&mut self, location: &FieldLocation) -> Result<(), HwpError> {
if location.nested_path.is_empty() {
self.document
.sections
.get(location.section_index)
.and_then(|section| section.paragraphs.get(location.para_index))
.ok_or_else(|| HwpError::InvalidField("필드 소유 본문 문단 범위 초과".into()))?;
return Ok(());
}
let path = Self::field_nested_reflow_path(location)?;
self.get_cell_paragraph_mut_by_path(location.section_index, location.para_index, &path)?;
Ok(())
}
fn reflow_field_location_after_edit(
&mut self,
location: &FieldLocation,
stored_end_for_reset: Option<i32>,
) -> Result<(), HwpError> {
if location.nested_path.is_empty() {
self.reflow_paragraph(location.section_index, location.para_index);
let hwp3_layout = self.document.layout_profile().hwp3_layout();
crate::renderer::composer::recalculate_section_vpos(
&mut self.document.sections[location.section_index].paragraphs,
location.para_index,
None,
stored_end_for_reset,
&self.styles,
self.dpi,
hwp3_layout,
);
let owner =
&self.document.sections[location.section_index].paragraphs[location.para_index];
if owner.line_segs.is_empty() {
return Err(HwpError::InvalidField(
"필드 소유 본문 문단 재조판 결과가 비어 있음".into(),
));
}
return Ok(());
}
let path = Self::field_nested_reflow_path(location)?;
let inner_para = path
.last()
.map(|entry| entry.2)
.ok_or_else(|| HwpError::InvalidField("필드 소유 문단 경로 없음".into()))?;
self.reflow_cell_paragraph_by_path(
location.section_index,
location.para_index,
&path,
inner_para,
);
self.recalculate_cell_paragraph_vpos_by_path(
location.section_index,
location.para_index,
&path,
inner_para,
None,
);
if self
.get_cell_paragraph_mut_by_path(location.section_index, location.para_index, &path)?
.line_segs
.is_empty()
{
return Err(HwpError::InvalidField(
"필드 소유 중첩 문단 재조판 결과가 비어 있음".into(),
));
}
self.mark_cell_control_dirty(location.section_index, location.para_index, path[0].0);
Ok(())
}
pub fn insert_click_here_field_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
pos: usize,
guide: &str,
memo: &str,
name: &str,
editable: bool,
) -> Result<String, HwpError> {
if list_id == ROOT_LIST_ID {
let (section_index, para_index) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField("본문 문단 인덱스 초과".into()))?;
let char_offset = char_idx_at_code_unit(
&self.document.sections[section_index].paragraphs[para_index],
pos,
);
return self.insert_click_here_field_at(
section_index,
para_index,
char_offset,
guide,
memo,
name,
editable,
);
}
let (_, lists) = self.collect_fields_and_lists();
let path = cell_path_to_list(&lists, list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let section_index = entry.section_index;
let host_para = root_para_of(&lists, entry);
let char_offset = self
.cell_paragraph_at_path(section_index, host_para, &path)
.map(|p| char_idx_at_code_unit(p, pos))
.unwrap_or(0);
self.insert_click_here_field_at_by_path(
section_index,
host_para,
&path,
char_offset,
guide,
memo,
name,
editable,
)
}
fn cell_paragraph_at_path(
&self,
section_index: usize,
host_para: usize,
path: &[(usize, usize, usize)],
) -> Option<&Paragraph> {
let mut para = self
.document
.sections
.get(section_index)?
.paragraphs
.get(host_para)?;
for (control_index, cell_index, para_index) in path {
let ctrl = para.controls.get(*control_index)?;
para = match ctrl {
Control::Table(table) => {
table.cells.get(*cell_index)?.paragraphs.get(*para_index)?
}
Control::Shape(shape) => shape_lists(shape)
.into_iter()
.find(|(node, _)| node == cell_index)
.and_then(|(_, paragraphs)| paragraphs.get(*para_index))?,
_ => return None,
};
}
Some(para)
}
pub fn rename_field_by_name(
&mut self,
oldname: &str,
newname: &str,
) -> Result<String, HwpError> {
if oldname.is_empty() {
return Err(HwpError::InvalidField("바꿀 필드 이름이 비어 있음".into()));
}
let targets: Vec<(FieldLocation, usize, bool)> = self
.collect_all_fields()
.iter()
.filter(|fi| fi.field.field_name() == Some(oldname))
.map(|fi| {
(
fi.location.clone(),
fi.field_range_index,
fi.field.ctrl_id == 0,
)
})
.collect();
if targets.is_empty() {
return Ok(r#"{"ok":false,"renamed":0}"#.to_string());
}
let mut renamed = 0usize;
let mut touched_sections: Vec<usize> = Vec::new();
for (location, field_range_index, is_cell) in targets {
if is_cell {
let cell = self.cell_at_location_mut(&location)?;
cell.field_name = if newname.is_empty() {
None
} else {
Some(newname.to_string())
};
} else {
let para = self.get_para_mut_at_location(&location)?;
let control_idx = para
.field_ranges
.get(field_range_index)
.ok_or_else(|| HwpError::InvalidField("field_range 인덱스 초과".into()))?
.control_idx;
if let Some(Control::Field(field)) = para.controls.get_mut(control_idx) {
field.ctrl_data_name = if newname.is_empty() {
None
} else {
Some(newname.to_string())
};
}
write_ctrl_data_name(&mut para.ctrl_data_records, control_idx, newname);
}
renamed += 1;
if !touched_sections.contains(&location.section_index) {
touched_sections.push(location.section_index);
}
}
for section_index in touched_sections {
if let Some(sec) = self.document.sections.get_mut(section_index) {
sec.raw_stream = None;
}
}
Ok(format!("{{\"ok\":true,\"renamed\":{}}}", renamed))
}
fn cell_at_location_mut(
&mut self,
location: &FieldLocation,
) -> Result<&mut crate::model::table::Cell, HwpError> {
let (control_index, cell_index) = match location.nested_path.last() {
Some(NestedEntry::TableCell {
control_index,
cell_index,
..
}) => (*control_index, *cell_index),
_ => return Err(HwpError::InvalidField("셀 필드가 아닌 위치".into())),
};
let mut host = location.clone();
host.nested_path.pop();
let para = self.get_para_mut_at_location(&host)?;
let ctrl = para
.controls
.get_mut(control_index)
.ok_or_else(|| HwpError::InvalidField("컨트롤 인덱스 초과".into()))?;
match ctrl {
Control::Table(table) => table
.cells
.get_mut(cell_index)
.ok_or_else(|| HwpError::InvalidField("셀 인덱스 초과".into())),
_ => Err(HwpError::InvalidField(
"셀을 담은 컨트롤이 표가 아님".into(),
)),
}
}
fn set_cell_field_text(
&mut self,
location: &FieldLocation,
value: &str,
) -> Result<(), HwpError> {
if location.nested_path.is_empty() {
return Err(HwpError::InvalidField(
"셀 필드 위치에 중첩 경로 없음".into(),
));
}
let sec = self
.document
.sections
.get_mut(location.section_index)
.ok_or_else(|| HwpError::InvalidField("구역 초과".into()))?;
let mut para: &mut Paragraph = sec
.paragraphs
.get_mut(location.para_index)
.ok_or_else(|| HwpError::InvalidField("문단 초과".into()))?;
for (i, entry) in location.nested_path[..location.nested_path.len() - 1]
.iter()
.enumerate()
{
para = match entry {
NestedEntry::TableCell {
control_index,
cell_index,
para_index,
} => {
let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 컨트롤 인덱스 {} 초과",
i, control_index
))
})?;
if let Control::Table(ref mut table) = ctrl {
let cell = table.cells.get_mut(*cell_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 셀 인덱스 {} 초과",
i, cell_index
))
})?;
cell.paragraphs.get_mut(*para_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 셀 문단 인덱스 {} 초과",
i, para_index
))
})?
} else {
return Err(HwpError::InvalidField(format!(
"경로[{}]: controls[{}]가 Table이 아님",
i, control_index
)));
}
}
NestedEntry::TextBox {
control_index,
para_index,
} => {
let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 컨트롤 인덱스 {} 초과",
i, control_index
))
})?;
if let Control::Shape(ref mut shape) = ctrl {
let drawing = shape.drawing_mut().ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: Shape에 DrawingObjAttr 없음",
i
))
})?;
let tb = drawing.text_box.as_mut().ok_or_else(|| {
HwpError::InvalidField(format!("경로[{}]: Shape에 TextBox 없음", i))
})?;
tb.paragraphs.get_mut(*para_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 글상자 문단 인덱스 {} 초과",
i, para_index
))
})?
} else {
return Err(HwpError::InvalidField(format!(
"경로[{}]: controls[{}]가 Shape가 아님",
i, control_index
)));
}
}
};
}
let last_idx = location.nested_path.len() - 1;
let last = location.nested_path.last().unwrap();
match last {
NestedEntry::TableCell {
control_index,
cell_index,
..
} => {
let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 컨트롤 인덱스 {} 초과",
last_idx, control_index
))
})?;
if let Control::Table(ref mut table) = ctrl {
let cell = table.cells.get_mut(*cell_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 셀 인덱스 {} 초과",
last_idx, cell_index
))
})?;
let cell_para = cell.paragraphs.first_mut().ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 셀 필드에 편집할 문단 없음",
last_idx
))
})?;
let old_len = cell_para.text.chars().count();
cell_para.replace_text_keeping_slots(0, old_len, value, None, false);
cell_para.replace_line_segs(Vec::new());
Ok(())
} else {
Err(HwpError::InvalidField(format!(
"경로[{}]: controls[{}]가 Table이 아님",
last_idx, control_index
)))
}
}
_ => Err(HwpError::InvalidField("셀 필드가 아닌 위치".into())),
}
}
fn set_field_text_at(
&mut self,
location: &FieldLocation,
field_range_index: usize,
value: &str,
) -> Result<(), HwpError> {
if let Some(sec) = self.document.sections.get_mut(location.section_index) {
sec.raw_stream = None;
}
let para = self.get_para_mut_at_location(location)?;
Self::replace_field_text_model(para, field_range_index, value)
}
pub(crate) fn replace_field_text_model(
para: &mut Paragraph,
field_range_index: usize,
value: &str,
) -> Result<(), HwpError> {
let fr = para
.field_ranges
.get(field_range_index)
.ok_or_else(|| HwpError::InvalidField("field_range 인덱스 초과".into()))?
.clone();
let start_idx = fr.start_char_idx;
let count = fr.end_char_idx.saturating_sub(start_idx);
let control_idx = fr.control_idx;
para.replace_text_keeping_slots(start_idx, count, value, Some(control_idx), false);
if !value.is_empty() {
if let Some(Control::Field(field)) = para.controls.get_mut(control_idx) {
field.properties |= 1 << 15;
}
}
para.replace_line_segs(Vec::new());
Ok(())
}
fn get_para_mut_at_location(
&mut self,
location: &FieldLocation,
) -> Result<&mut Paragraph, HwpError> {
let sec = self
.document
.sections
.get_mut(location.section_index)
.ok_or_else(|| HwpError::InvalidField("구역 인덱스 초과".into()))?;
let mut para = sec
.paragraphs
.get_mut(location.para_index)
.ok_or_else(|| HwpError::InvalidField("문단 인덱스 초과".into()))?;
for (i, entry) in location.nested_path.iter().enumerate() {
para = match entry {
NestedEntry::TableCell {
control_index,
cell_index,
para_index,
} => {
let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 컨트롤 인덱스 {} 초과",
i, control_index
))
})?;
if let Control::Table(ref mut table) = ctrl {
let cell = table.cells.get_mut(*cell_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 셀 인덱스 {} 초과",
i, cell_index
))
})?;
cell.paragraphs.get_mut(*para_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 셀 문단 인덱스 {} 초과",
i, para_index
))
})?
} else {
return Err(HwpError::InvalidField(format!(
"경로[{}]: controls[{}]가 Table이 아님",
i, control_index
)));
}
}
NestedEntry::TextBox {
control_index,
para_index,
} => {
let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 컨트롤 인덱스 {} 초과",
i, control_index
))
})?;
if let Control::Shape(ref mut shape) = ctrl {
let drawing = shape.drawing_mut().ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: Shape에 DrawingObjAttr 없음",
i
))
})?;
let tb = drawing.text_box.as_mut().ok_or_else(|| {
HwpError::InvalidField(format!("경로[{}]: Shape에 TextBox 없음", i))
})?;
tb.paragraphs.get_mut(*para_index).ok_or_else(|| {
HwpError::InvalidField(format!(
"경로[{}]: 글상자 문단 인덱스 {} 초과",
i, para_index
))
})?
} else {
return Err(HwpError::InvalidField(format!(
"경로[{}]: controls[{}]가 Shape가 아님",
i, control_index
)));
}
}
};
}
Ok(para)
}
pub fn remove_field_at(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
) -> Result<String, HwpError> {
let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
self.document
.sections
.get(section_idx)
.and_then(|section| section.paragraphs.get(para_idx))
.ok_or_else(|| HwpError::InvalidField("문단 위치 초과".into()))?,
);
let para = self
.document
.sections
.get_mut(section_idx)
.and_then(|s| s.paragraphs.get_mut(para_idx))
.ok_or_else(|| HwpError::InvalidField("문단 위치 초과".into()))?;
let removed = remove_field_in_para(para, char_offset)?;
let mut clear_active = false;
if let Some(active) = self.active_field.as_mut() {
if active.section_idx == section_idx && active.para_idx == para_idx {
match &active.cell_path {
None if active.para_idx == para_idx => {
clear_active = active.control_idx == removed;
if active.control_idx > removed {
active.control_idx -= 1;
}
}
Some(path) => {
clear_active = path.first().is_some_and(|&(table, _, _)| table > removed)
}
None => {}
}
}
}
if clear_active {
self.clear_active_field();
}
if let Some(section) = self.document.sections.get_mut(section_idx) {
section.raw_stream = None;
}
self.reflow_paragraph(section_idx, para_idx);
let hwp3_layout = self.document.layout_profile().hwp3_layout();
crate::renderer::composer::recalculate_section_vpos(
&mut self.document.sections[section_idx].paragraphs,
para_idx,
None,
stored_end_for_reset,
&self.styles,
self.dpi,
hwp3_layout,
);
self.recompose_section(section_idx);
self.paginate();
Ok(r#"{"ok":true}"#.to_string())
}
pub fn remove_field_at_in_cell(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: usize,
cell_para_idx: usize,
char_offset: usize,
is_textbox: bool,
) -> Result<String, HwpError> {
let para = {
let host = self
.document
.sections
.get_mut(section_idx)
.and_then(|s| s.paragraphs.get_mut(parent_para_idx))
.ok_or_else(|| HwpError::InvalidField("호스트 문단 위치 초과".into()))?;
let ctrl = host
.controls
.get_mut(control_idx)
.ok_or_else(|| HwpError::InvalidField("컨트롤 인덱스 초과".into()))?;
if is_textbox {
if let Control::Shape(shape) = ctrl {
let drawing = shape.drawing_mut().ok_or_else(|| {
HwpError::InvalidField("Shape에 DrawingObjAttr 없음".into())
})?;
let tb = drawing
.text_box
.as_mut()
.ok_or_else(|| HwpError::InvalidField("Shape에 TextBox 없음".into()))?;
tb.paragraphs
.get_mut(cell_para_idx)
.ok_or_else(|| HwpError::InvalidField("글상자 문단 인덱스 초과".into()))?
} else {
return Err(HwpError::InvalidField("예상된 Shape 컨트롤이 아님".into()));
}
} else {
if let Control::Table(table) = ctrl {
let cell = table
.cells
.get_mut(cell_idx)
.ok_or_else(|| HwpError::InvalidField("셀 인덱스 초과".into()))?;
cell.paragraphs
.get_mut(cell_para_idx)
.ok_or_else(|| HwpError::InvalidField("셀 문단 인덱스 초과".into()))?
} else {
return Err(HwpError::InvalidField("예상된 Table 컨트롤이 아님".into()));
}
}
};
let removed = remove_field_in_para(para, char_offset)?;
if self.active_field.as_ref().is_some_and(|active| {
active.section_idx == section_idx
&& active.para_idx == parent_para_idx
&& active.cell_path.as_deref().is_some_and(|path| {
path.first() == Some(&(control_idx, cell_idx, cell_para_idx))
&& path
.get(1)
.map_or(active.control_idx, |&(table, _, _)| table)
>= removed
})
}) {
self.clear_active_field();
}
if let Some(section) = self.document.sections.get_mut(section_idx) {
section.raw_stream = None;
}
self.reflow_cell_paragraph(
section_idx,
parent_para_idx,
control_idx,
cell_idx,
cell_para_idx,
);
self.recompose_section(section_idx);
self.paginate();
Ok(r#"{"ok":true}"#.to_string())
}
pub fn set_active_field(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
) -> bool {
use super::super::ActiveFieldInfo;
let ctrl_idx = self.find_field_control_idx(section_idx, para_idx, char_offset, None);
if let Some(ci) = ctrl_idx {
let new_info = ActiveFieldInfo {
section_idx,
para_idx,
control_idx: ci,
cell_path: None,
};
if self.active_field.as_ref() != Some(&new_info) {
self.active_field = Some(new_info);
self.invalidate_page_tree_cache();
return true;
}
}
false
}
pub fn set_active_field_in_cell(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: usize,
cell_para_idx: usize,
char_offset: usize,
is_textbox: bool,
) -> bool {
use super::super::ActiveFieldInfo;
let cell_path = Some(vec![(control_idx, cell_idx, cell_para_idx)]);
let ctrl_idx = self.find_field_control_idx_in_cell(
section_idx,
parent_para_idx,
control_idx,
cell_idx,
cell_para_idx,
char_offset,
is_textbox,
);
if let Some(ci) = ctrl_idx {
let new_info = ActiveFieldInfo {
section_idx,
para_idx: parent_para_idx,
control_idx: ci,
cell_path,
};
if self.active_field.as_ref() != Some(&new_info) {
self.active_field = Some(new_info);
self.invalidate_page_tree_cache();
return true;
}
}
false
}
pub fn clear_active_field(&mut self) {
if self.active_field.is_some() {
self.active_field = None;
self.invalidate_page_tree_cache();
}
}
pub fn get_field_info_at(
&self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
) -> String {
let para = match self
.document
.sections
.get(section_idx)
.and_then(|s| s.paragraphs.get(para_idx))
{
Some(p) => p,
None => return r#"{"inField":false}"#.to_string(),
};
field_info_at_in_para(para, char_offset)
}
pub fn get_field_info_at_in_cell(
&self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: usize,
cell_para_idx: usize,
char_offset: usize,
is_textbox: bool,
) -> String {
let para = (|| {
let host = self
.document
.sections
.get(section_idx)?
.paragraphs
.get(parent_para_idx)?;
let ctrl = host.controls.get(control_idx)?;
if is_textbox {
if let Control::Shape(shape) = ctrl {
let tb = shape.drawing()?.text_box.as_ref()?;
return tb.paragraphs.get(cell_para_idx);
}
} else {
if let Control::Table(table) = ctrl {
let cell = table.cells.get(cell_idx)?;
return cell.paragraphs.get(cell_para_idx);
}
}
None
})();
match para {
Some(p) => field_info_at_in_para(p, char_offset),
None => r#"{"inField":false}"#.to_string(),
}
}
pub fn get_field_info_at_by_path(
&self,
section_idx: usize,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
char_offset: usize,
) -> String {
match self.resolve_paragraph_by_path(section_idx, parent_para_idx, path) {
Ok(para) => field_info_at_in_para(para, char_offset),
Err(_) => r#"{"inField":false}"#.to_string(),
}
}
pub fn set_active_field_by_path(
&mut self,
section_idx: usize,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
char_offset: usize,
) -> bool {
use super::super::ActiveFieldInfo;
let para = match self.resolve_paragraph_by_path(section_idx, parent_para_idx, path) {
Ok(p) => p,
Err(_) => return false,
};
let ctrl_idx = find_field_ctrl_idx_in_para(para, char_offset);
if let Some(ci) = ctrl_idx {
let cell_path = Some(path.to_vec());
let new_info = ActiveFieldInfo {
section_idx,
para_idx: parent_para_idx,
control_idx: ci,
cell_path,
};
if self.active_field.as_ref() != Some(&new_info) {
self.active_field = Some(new_info);
self.invalidate_page_tree_cache();
return true;
}
}
false
}
}
fn field_info_at_in_para(para: &Paragraph, char_offset: usize) -> String {
for fr in ¶.field_ranges {
if fr.start_char_idx != fr.end_char_idx || char_offset != fr.start_char_idx {
continue;
}
if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
if field.field_type != FieldType::ClickHere {
continue;
}
let guide = field.guide_text().unwrap_or("");
return format!(
"{{\"inField\":true,\"fieldId\":{},\"fieldType\":\"{}\",\"startCharIdx\":{},\"endCharIdx\":{},\"isGuide\":true,\"guideName\":{},\"editableInForm\":{}}}",
field.field_id,
field.field_type_str(),
fr.start_char_idx,
fr.end_char_idx,
json_escape(guide),
field.is_editable_in_form(),
);
}
}
for fr in ¶.field_ranges {
if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
if field.field_type != FieldType::ClickHere {
continue;
}
if char_offset >= fr.start_char_idx && char_offset <= fr.end_char_idx {
let is_guide = fr.start_char_idx == fr.end_char_idx;
let guide = field.guide_text().unwrap_or("");
return format!(
"{{\"inField\":true,\"fieldId\":{},\"fieldType\":\"{}\",\"startCharIdx\":{},\"endCharIdx\":{},\"isGuide\":{},\"guideName\":{},\"editableInForm\":{}}}",
field.field_id,
field.field_type_str(),
fr.start_char_idx,
fr.end_char_idx,
is_guide,
json_escape(guide),
field.is_editable_in_form(),
);
}
}
}
r#"{"inField":false}"#.to_string()
}
fn collect_fields_from_paragraph(
para: &Paragraph,
base_location: &FieldLocation,
list_id: u32,
para_in_list: usize,
walk: &mut ListWalk,
result: &mut Vec<FieldInfo>,
) {
let host_para_index = if list_id == ROOT_LIST_ID {
base_location.para_index
} else {
para_in_list
};
for (fri, fr) in para.field_ranges.iter().enumerate() {
if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
let value = if fr.start_char_idx < fr.end_char_idx {
let chars: Vec<char> = para.text.chars().collect();
if fr.end_char_idx <= chars.len() {
chars[fr.start_char_idx..fr.end_char_idx].iter().collect()
} else {
String::new()
}
} else {
String::new()
};
result.push(FieldInfo {
field: field.clone(),
location: base_location.clone(),
value,
field_range_index: fri,
list_id,
para_in_list,
start_pos: field_content_start(para, fri),
end_pos: field_content_start(para, fri)
+ if fr.start_char_idx == fr.end_char_idx {
guide_units(para, fr.control_idx)
} else {
fr.end_char_idx - fr.start_char_idx
},
});
}
}
for (ci, ctrl) in para.controls.iter().enumerate() {
match ctrl {
Control::Table(table) => {
for (cell_i, cell) in table.cells.iter().enumerate() {
let cell_list_id = walk.alloc();
walk.lists.push(ListEntry {
list_id: cell_list_id,
is_cell: true,
host_list_id: list_id,
section_index: base_location.section_index,
host_para_index,
control_index: ci,
cell_index: cell_i,
para_count: cell.paragraphs.len(),
grid: Some(CellGrid {
row: cell.row,
col: cell.col,
row_span: cell.row_span,
col_span: cell.col_span,
cell_count: table.cells.len(),
}),
});
if let Some(ref fname) = cell.field_name {
let mut loc = base_location.clone();
loc.nested_path.push(NestedEntry::TableCell {
control_index: ci,
cell_index: cell_i,
para_index: 0,
});
let value = cell
.paragraphs
.first()
.map(|p| p.text.clone())
.unwrap_or_default();
result.push(FieldInfo {
field: Field {
ctrl_id: 0,
field_id: (ci as u32) << 16 | cell_i as u32,
field_type: FieldType::ClickHere,
command: String::new(),
properties: if cell.editable_in_form() { 1 } else { 0 },
extra_properties: 0,
ctrl_data_name: Some(fname.clone()),
instance_id: None,
raw_type: None,
memo_index: 0,
memo_paragraphs: Vec::new(),
memo_text_direction: None,
raw_parameters_xml: None,
parameters: Default::default(),
guide_residue: None,
hyperlink_format: None,
},
location: loc,
value,
field_range_index: 0,
list_id: cell_list_id,
para_in_list: 0,
start_pos: 0,
end_pos: 0,
});
}
for (pi, cell_para) in cell.paragraphs.iter().enumerate() {
let mut loc = base_location.clone();
loc.nested_path.push(NestedEntry::TableCell {
control_index: ci,
cell_index: cell_i,
para_index: pi,
});
collect_fields_from_paragraph(
cell_para,
&loc,
cell_list_id,
pi,
walk,
result,
);
}
}
}
Control::Shape(shape) => {
for (node, paragraphs) in shape_lists(shape) {
let box_list_id = walk.alloc();
walk.lists.push(ListEntry {
list_id: box_list_id,
is_cell: false,
host_list_id: list_id,
section_index: base_location.section_index,
host_para_index,
control_index: ci,
cell_index: node,
para_count: paragraphs.len(),
grid: None,
});
for (pi, tb_para) in paragraphs.iter().enumerate() {
let mut loc = base_location.clone();
loc.nested_path.push(NestedEntry::TextBox {
control_index: ci,
para_index: pi,
});
collect_fields_from_paragraph(tb_para, &loc, box_list_id, pi, walk, result);
}
}
}
_ => {}
}
}
}
pub(crate) fn cell_path_to_list(
lists: &[ListEntry],
list_id: u32,
para_in_list: usize,
) -> Option<Vec<(usize, usize, usize)>> {
let mut path = Vec::new();
let mut current = lists.iter().find(|l| l.list_id == list_id)?;
let mut para_index = para_in_list;
loop {
path.push((current.control_index, current.cell_index, para_index));
if current.host_list_id == ROOT_LIST_ID {
break;
}
para_index = current.host_para_index;
current = lists.iter().find(|l| l.list_id == current.host_list_id)?;
}
path.reverse();
Some(path)
}
pub(crate) fn root_para_of(lists: &[ListEntry], entry: &ListEntry) -> usize {
let mut current = entry;
while current.host_list_id != ROOT_LIST_ID {
match lists.iter().find(|l| l.list_id == current.host_list_id) {
Some(host) => current = host,
None => break,
}
}
current.host_para_index
}
pub(crate) fn cursor_paragraph<'a>(
core: &'a DocumentCore,
lists: &[ListEntry],
list_id: u32,
para_in_list: usize,
) -> Option<&'a Paragraph> {
if list_id == ROOT_LIST_ID {
let (si, pi) = root_para_location(core, para_in_list)?;
return core.document.sections.get(si)?.paragraphs.get(pi);
}
let entry = lists.iter().find(|l| l.list_id == list_id)?;
let path = cell_path_to_list(lists, list_id, para_in_list)?;
core.cell_paragraph_at_path(entry.section_index, root_para_of(lists, entry), &path)
}
pub(crate) fn root_para_location(
core: &DocumentCore,
para_in_list: usize,
) -> Option<(usize, usize)> {
let mut rest = para_in_list;
for (si, sec) in core.document.sections.iter().enumerate() {
if rest < sec.paragraphs.len() {
return Some((si, rest));
}
rest -= sec.paragraphs.len();
}
None
}
pub(crate) fn root_para_count(core: &DocumentCore) -> usize {
core.document
.sections
.iter()
.map(|s| s.paragraphs.len())
.sum()
}
pub(crate) fn char_idx_at_code_unit(para: &Paragraph, pos: usize) -> usize {
match para
.char_offsets
.iter()
.position(|offset| *offset as usize >= pos)
{
Some(idx) => idx,
None => para.char_offsets.len(),
}
}
pub(crate) fn leading_anchor_pos(para: &Paragraph) -> usize {
let mut skipped = 0usize;
let mut anchored_count = 0usize;
for ctrl in ¶.controls {
let anchored = match ctrl {
Control::Table(t) => !t.common.treat_as_char,
Control::Shape(s) => !s.common().treat_as_char,
Control::Field(_) => false,
Control::AutoNumber(_) | Control::NewNumber(_) => false,
_ => true,
};
if !anchored {
break;
}
skipped += 8;
anchored_count += 1;
}
if anchored_count > 0 {
if let Some(first_char) = para.char_offsets.first() {
let first_char = *first_char as usize;
if first_char > 0 && first_char < skipped {
skipped = first_char;
}
}
}
skipped.min((para.char_count as usize).saturating_sub(1))
}
pub(crate) const EXTENDED_CTRL_UNITS: usize = 8;
pub(crate) fn select_start_pos(para: &Paragraph) -> usize {
para.controls
.iter()
.take_while(|ctrl| matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)))
.count()
* EXTENDED_CTRL_UNITS
}
pub(crate) fn stream_pos(para: &Paragraph, char_idx: usize) -> usize {
let control_positions = para.control_text_positions();
let mut units = char_idx + tab_padding(para, char_idx);
for (ci, ctrl) in para.controls.iter().enumerate() {
if matches!(ctrl, Control::Field(_)) {
continue;
}
if control_positions
.get(ci)
.is_some_and(|pos| *pos <= char_idx)
{
units += ctrl_stream_units(ctrl);
}
}
for fr in ¶.field_ranges {
if fr.start_char_idx <= char_idx {
units += EXTENDED_CTRL_UNITS;
}
if fr.end_char_idx <= char_idx {
units += EXTENDED_CTRL_UNITS;
if fr.start_char_idx == fr.end_char_idx {
units += guide_units(para, fr.control_idx);
}
}
}
units
}
pub(crate) fn shape_lists(shape: &crate::model::shape::ShapeObject) -> Vec<(usize, &[Paragraph])> {
let mut out: Vec<(usize, &[Paragraph])> = Vec::new();
if let Some(tb) = shape.drawing().and_then(|d| d.text_box.as_ref()) {
out.push((0, tb.paragraphs.as_slice()));
}
let caption = match shape {
crate::model::shape::ShapeObject::Group(g) => g.caption.as_ref(),
other => other.drawing().and_then(|d| d.caption.as_ref()),
};
if let Some(cap) = caption {
if !cap.paragraphs.is_empty() {
out.push((1, cap.paragraphs.as_slice()));
}
}
out
}
fn ctrl_stream_units(ctrl: &Control) -> usize {
match ctrl {
Control::AutoNumber(_) | Control::NewNumber(_) => EXTENDED_CTRL_UNITS - 1,
_ => EXTENDED_CTRL_UNITS,
}
}
fn tab_padding(para: &Paragraph, char_idx: usize) -> usize {
para.text
.chars()
.take(char_idx)
.filter(|c| *c == '\t')
.count()
* (EXTENDED_CTRL_UNITS - 1)
}
fn guide_units(para: &Paragraph, control_idx: usize) -> usize {
match para.controls.get(control_idx) {
Some(Control::Field(field)) => field.guide_text().map(|g| g.chars().count()).unwrap_or(0),
_ => 0,
}
}
pub(crate) fn stream_len(para: &Paragraph) -> usize {
stream_pos(para, para.text.chars().count()).max(leading_anchor_pos(para))
}
pub(crate) fn field_content_start(para: &Paragraph, field_range_index: usize) -> usize {
let Some(own) = para.field_ranges.get(field_range_index) else {
return 0;
};
let control_positions = para.control_text_positions();
let mut units = own.start_char_idx + tab_padding(para, own.start_char_idx);
for (ci, ctrl) in para.controls.iter().enumerate() {
if matches!(ctrl, Control::Field(_)) {
continue;
}
if control_positions
.get(ci)
.is_some_and(|pos| *pos <= own.start_char_idx)
{
units += ctrl_stream_units(ctrl);
}
}
for (i, fr) in para.field_ranges.iter().enumerate() {
if i == field_range_index {
continue; }
if fr.start_char_idx <= own.start_char_idx {
units += EXTENDED_CTRL_UNITS;
}
if fr.end_char_idx <= own.start_char_idx {
units += EXTENDED_CTRL_UNITS;
if fr.start_char_idx == fr.end_char_idx {
units += guide_units(para, fr.control_idx);
}
}
}
units + EXTENDED_CTRL_UNITS }
pub(crate) fn caret_stops(para: &Paragraph) -> Vec<usize> {
let mut stops = Vec::new();
for (fri, _) in para.field_ranges.iter().enumerate() {
let content = field_content_start(para, fri);
stops.push(content.saturating_sub(EXTENDED_CTRL_UNITS)); stops.push(content);
}
let len = para.text.chars().count();
for i in 0..len {
stops.push(stream_pos(para, i));
}
stops.push(stream_len(para));
stops.sort_unstable();
stops.dedup();
stops
}
pub(crate) fn word_starts(para: &Paragraph) -> Vec<usize> {
let mut starts = vec![leading_anchor_pos(para)];
for (fri, _) in para.field_ranges.iter().enumerate() {
let content = field_content_start(para, fri);
starts.push(content.saturating_sub(EXTENDED_CTRL_UNITS));
starts.push(content);
}
let chars: Vec<char> = para.text.chars().collect();
for i in 1..chars.len() {
if chars[i - 1].is_whitespace()
&& !chars[i].is_whitespace()
&& stream_pos(para, i) == stream_pos(para, i - 1) + 1
{
starts.push(stream_pos(para, i));
}
}
starts.push(stream_len(para));
starts.sort_unstable();
starts.dedup();
starts
}
pub(crate) fn word_end_from(para: &Paragraph, pos: usize) -> usize {
let chars: Vec<char> = para.text.chars().collect();
for (i, ch) in chars.iter().enumerate() {
let at = stream_pos(para, i);
if at >= pos && ch.is_whitespace() {
return at;
}
}
stream_len(para)
}
pub(crate) fn char_idx_at_stream_pos(para: &Paragraph, pos: usize) -> usize {
let len = para.text.chars().count();
(0..=len)
.find(|&i| stream_pos(para, i) >= pos)
.unwrap_or(len)
}
#[allow(dead_code)]
fn code_unit_pos(para: &Paragraph, char_idx: usize, control_idx: usize) -> usize {
if let Some(offset) = para.char_offsets.get(char_idx) {
return *offset as usize;
}
if para.char_offsets.is_empty() {
let before: usize = para
.controls
.iter()
.take(control_idx)
.map(|c| {
if matches!(c, Control::Field(_)) {
16
} else {
8
}
})
.sum();
return before + 8; }
para.char_offsets
.last()
.map(|last| *last as usize + 1)
.unwrap_or_else(|| (para.char_count as usize).saturating_sub(1))
}
pub(crate) fn write_ctrl_data_name(
records: &mut Vec<Option<Vec<u8>>>,
control_idx: usize,
new_name: &str,
) {
while records.len() <= control_idx {
records.push(None);
}
let name_chars: Vec<u16> = new_name.encode_utf16().collect();
let mut data = match &records[control_idx] {
Some(existing) if existing.len() >= 12 => existing[..10].to_vec(),
Some(_) => return, None => vec![0x1Bu8, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00],
};
data.extend_from_slice(&(name_chars.len() as u16).to_le_bytes());
for ch in &name_chars {
data.extend_from_slice(&ch.to_le_bytes());
}
records[control_idx] = Some(data);
}
fn field_location_json(loc: &FieldLocation) -> String {
if loc.nested_path.is_empty() {
format!(
"{{\"sectionIndex\":{},\"paraIndex\":{}}}",
loc.section_index, loc.para_index,
)
} else {
let path_entries: Vec<String> = loc.nested_path.iter().map(|e| match e {
NestedEntry::TableCell { control_index, cell_index, para_index } => {
format!("{{\"type\":\"cell\",\"controlIndex\":{},\"cellIndex\":{},\"paraIndex\":{}}}",
control_index, cell_index, para_index)
}
NestedEntry::TextBox { control_index, para_index } => {
format!("{{\"type\":\"textbox\",\"controlIndex\":{},\"paraIndex\":{}}}",
control_index, para_index)
}
}).collect();
format!(
"{{\"sectionIndex\":{},\"paraIndex\":{},\"path\":[{}]}}",
loc.section_index,
loc.para_index,
path_entries.join(","),
)
}
}
fn para_at_location<'a>(core: &'a DocumentCore, location: &FieldLocation) -> Option<&'a Paragraph> {
let mut para = core
.document
.sections
.get(location.section_index)?
.paragraphs
.get(location.para_index)?;
for entry in &location.nested_path {
para = match entry {
NestedEntry::TableCell {
control_index,
cell_index,
para_index,
} => {
let ctrl = para.controls.get(*control_index)?;
if let Control::Table(table) = ctrl {
table.cells.get(*cell_index)?.paragraphs.get(*para_index)?
} else {
return None;
}
}
NestedEntry::TextBox {
control_index,
para_index,
} => {
let ctrl = para.controls.get(*control_index)?;
if let Control::Shape(shape) = ctrl {
shape
.drawing()?
.text_box
.as_ref()?
.paragraphs
.get(*para_index)?
} else {
return None;
}
}
};
}
Some(para)
}
fn field_range_bounds(core: &DocumentCore, fi: &FieldInfo) -> Option<(usize, usize)> {
let para = para_at_location(core, &fi.location)?;
let range = para.field_ranges.get(fi.field_range_index)?;
Some((range.start_char_idx, range.end_char_idx))
}
impl DocumentCore {
fn find_field_control_idx(
&self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
_cell_path: Option<(usize, usize, usize)>,
) -> Option<usize> {
let para = self
.document
.sections
.get(section_idx)?
.paragraphs
.get(para_idx)?;
find_field_ctrl_idx_in_para(para, char_offset)
}
fn find_field_control_idx_in_cell(
&self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: usize,
cell_para_idx: usize,
char_offset: usize,
is_textbox: bool,
) -> Option<usize> {
let host = self
.document
.sections
.get(section_idx)?
.paragraphs
.get(parent_para_idx)?;
let ctrl = host.controls.get(control_idx)?;
let para = if is_textbox {
if let Control::Shape(shape) = ctrl {
let tb = shape.drawing()?.text_box.as_ref()?;
tb.paragraphs.get(cell_para_idx)?
} else {
return None;
}
} else {
if let Control::Table(table) = ctrl {
table.cells.get(cell_idx)?.paragraphs.get(cell_para_idx)?
} else {
return None;
}
};
find_field_ctrl_idx_in_para(para, char_offset)
}
pub(crate) fn next_click_here_field_id(&self) -> u32 {
let mut max_id = 0u32;
for section in &self.document.sections {
for para in §ion.paragraphs {
collect_max_field_id(para, &mut max_id);
}
}
max_id.saturating_add(1).max(1)
}
}
pub(crate) fn collect_max_field_id(para: &Paragraph, max_id: &mut u32) {
for end in ¶.orphan_field_ends {
*max_id = (*max_id).max(end.begin_id_ref).max(end.field_id);
}
for range in ¶.field_ranges {
*max_id = (*max_id).max(range.end_field_id);
}
for ctrl in ¶.controls {
match ctrl {
Control::Field(field) => {
*max_id = (*max_id)
.max(field.field_id)
.max(field.instance_id.unwrap_or(0));
for p in &field.memo_paragraphs {
collect_max_field_id(p, max_id);
}
}
Control::Header(h) => {
for p in &h.paragraphs {
collect_max_field_id(p, max_id);
}
}
Control::Footer(h) => {
for p in &h.paragraphs {
collect_max_field_id(p, max_id);
}
}
Control::Footnote(h) => {
for p in &h.paragraphs {
collect_max_field_id(p, max_id);
}
}
Control::Endnote(h) => {
for p in &h.paragraphs {
collect_max_field_id(p, max_id);
}
}
Control::HiddenComment(h) => {
for p in &h.paragraphs {
collect_max_field_id(p, max_id);
}
}
Control::SectionDef(s) => {
for m in &s.master_pages {
for p in &m.paragraphs {
collect_max_field_id(p, max_id);
}
}
}
Control::Table(table) => {
for cell in &table.cells {
for cell_para in &cell.paragraphs {
collect_max_field_id(cell_para, max_id);
}
}
if let Some(caption) = &table.caption {
for cap_para in &caption.paragraphs {
collect_max_field_id(cap_para, max_id);
}
}
}
Control::Shape(shape) => collect_shape_field_ids(shape, max_id),
Control::Picture(pic) => {
if let Some(caption) = &pic.caption {
for cap_para in &caption.paragraphs {
collect_max_field_id(cap_para, max_id);
}
}
}
_ => {}
}
}
}
fn collect_shape_field_ids(shape: &crate::model::shape::ShapeObject, max_id: &mut u32) {
use crate::model::shape::ShapeObject;
if let Some(drawing) = shape.drawing() {
if let Some(text_box) = &drawing.text_box {
for p in &text_box.paragraphs {
collect_max_field_id(p, max_id);
}
}
if let Some(caption) = &drawing.caption {
for p in &caption.paragraphs {
collect_max_field_id(p, max_id);
}
}
}
let caption = match shape {
ShapeObject::Group(g) => {
for child in &g.children {
collect_shape_field_ids(child, max_id);
}
g.caption.as_ref()
}
ShapeObject::Picture(p) => p.caption.as_ref(),
ShapeObject::Chart(c) => c.caption.as_ref(),
ShapeObject::Ole(o) => o.caption.as_ref(),
_ => None,
};
if let Some(caption) = caption {
for p in &caption.paragraphs {
collect_max_field_id(p, max_id);
}
}
}
fn insert_click_here_field_in_para(
para: &mut Paragraph,
char_offset: usize,
field_id: u32,
guide: &str,
memo: &str,
name: &str,
editable: bool,
) -> Result<usize, HwpError> {
let field = Field {
field_type: FieldType::ClickHere,
command: Field::build_clickhere_command(guide, memo),
properties: if editable { 1 } else { 0 },
extra_properties: 0x09,
field_id,
ctrl_id: tags::FIELD_CLICKHERE,
instance_id: None,
raw_type: None,
ctrl_data_name: if name.is_empty() {
None
} else {
Some(name.to_string())
},
memo_index: 0,
memo_paragraphs: Vec::new(),
memo_text_direction: None,
raw_parameters_xml: None,
parameters: Default::default(),
guide_residue: None,
hyperlink_format: None,
};
insert_field_in_para(para, char_offset, field).map(|(start, _)| start)
}
pub(crate) fn insert_field_in_para(
para: &mut Paragraph,
char_offset: usize,
field: Field,
) -> Result<(usize, usize), HwpError> {
let text_len = para.text.chars().count();
let start = char_offset.min(text_len);
let gaps = raw_slot_gaps(para)?;
let insert_pos = gaps[start].1;
let insert_idx = gaps[..=start]
.iter()
.map(|&(gap_start, gap_end)| ((gap_end - gap_start) / 8) as usize)
.sum::<usize>()
- para
.field_ranges
.iter()
.filter(|range| range.end_char_idx <= start)
.count();
for range in &mut para.field_ranges {
if range.control_idx >= insert_idx {
range.control_idx += 1;
}
}
para.controls.insert(insert_idx, Control::Field(field));
if para.ctrl_data_records.len() < insert_idx {
para.ctrl_data_records.resize(insert_idx, None);
}
para.ctrl_data_records.insert(insert_idx, None);
let new_range = FieldRange {
start_char_idx: start,
end_char_idx: start,
control_idx: insert_idx,
..Default::default()
};
let range_idx = para
.field_ranges
.iter()
.position(|range| {
range.start_char_idx > start
|| (range.start_char_idx == start && range.control_idx > insert_idx)
})
.unwrap_or(para.field_ranges.len());
para.field_ranges.insert(range_idx, new_range);
for offset in &mut para.char_offsets[start..] {
*offset += 16;
}
para.shift_position_metadata_for_stream_insertion(insert_pos, 16);
para.char_count = gaps[text_len].1 + 16 + 1;
para.invalidate_layout_inputs();
Ok((start, insert_idx))
}
fn find_field_ctrl_idx_in_para(para: &Paragraph, char_offset: usize) -> Option<usize> {
for fr in ¶.field_ranges {
if fr.start_char_idx == fr.end_char_idx && char_offset == fr.start_char_idx {
if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
if field.field_type == FieldType::ClickHere {
return Some(fr.control_idx);
}
}
}
}
for fr in ¶.field_ranges {
if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
if field.field_type != FieldType::ClickHere {
continue;
}
if char_offset >= fr.start_char_idx && char_offset <= fr.end_char_idx {
return Some(fr.control_idx);
}
}
}
None
}
fn remove_field_in_para(para: &mut Paragraph, char_offset: usize) -> Result<usize, HwpError> {
let control_idx = find_field_ctrl_idx_in_para(para, char_offset)
.ok_or_else(|| HwpError::InvalidField("커서 위치에 누름틀 필드 없음".into()))?;
remove_field_control_in_para(para, control_idx)
}
pub(crate) fn remove_field_control_in_para(
para: &mut Paragraph,
control_idx: usize,
) -> Result<usize, HwpError> {
let gaps = raw_slot_gaps(para)?;
let range_idx = para
.field_ranges
.iter()
.position(|range| range.control_idx == control_idx)
.ok_or_else(invalid_raw_slots)?;
let (start, end) = (
para.field_ranges[range_idx].start_char_idx,
para.field_ranges[range_idx].end_char_idx,
);
let content: u32 = para
.text
.chars()
.skip(start)
.take(end - start)
.map(|ch| if ch == '\t' { 8 } else { ch.len_utf16() as u32 })
.sum();
let merged = gaps[end].1 - gaps[start].0 - content;
let para_end = gaps[gaps.len() - 1].1 - content - 16;
para.field_ranges.remove(range_idx);
if end > start {
para.delete_text_at(start, end - start);
}
let slots = gaps[start].0 + merged - 16;
let shift = |position: &mut u32| {
if *position > slots {
*position = position.saturating_sub(16).max(slots);
}
};
for position in &mut para.char_offsets {
shift(position);
}
for shape in &mut para.char_shapes {
shift(&mut shape.start_pos);
}
for range in &mut para.range_tags {
shift(&mut range.start);
shift(&mut range.end);
}
for mark in &mut para.markpen_marks {
if let Some(position) = &mut mark.utf16_pos {
shift(position);
}
}
para.char_count = para_end + 1;
let shapes = std::mem::take(&mut para.char_shapes);
for shape in shapes {
if para
.char_shapes
.last()
.is_some_and(|last| last.start_pos == shape.start_pos)
{
para.char_shapes.pop();
}
para.char_shapes.push(shape);
}
para.invalidate_layout_inputs();
para.controls.remove(control_idx);
if control_idx < para.ctrl_data_records.len() {
para.ctrl_data_records.remove(control_idx);
}
for range in &mut para.field_ranges {
if range.control_idx > control_idx {
range.control_idx -= 1;
}
}
para.forget_para_text_if_emptied();
Ok(control_idx)
}
fn invalid_raw_slots() -> HwpError {
HwpError::InvalidField("누름틀의 원시 슬롯 위치를 확인할 수 없습니다.".into())
}
pub(crate) fn raw_slot_gaps(para: &Paragraph) -> Result<Vec<(u32, u32)>, HwpError> {
if !para.title_marks.is_empty()
|| !para.orphan_field_ends.is_empty()
|| para.text.contains('\u{fffc}')
|| para.char_offsets.len() != para.text.chars().count()
|| para.controls.iter().any(|control| {
matches!(
control,
Control::Hyperlink(_)
| Control::AutoNumber(_)
| Control::NewNumber(_)
| Control::Ruby(_)
| Control::CharOverlap(_)
| Control::Unknown(_)
)
})
{
return Err(invalid_raw_slots());
}
let mut gaps = Vec::with_capacity(para.char_offsets.len() + 1);
let mut end = 0u32;
let mut inner = 0;
for (&offset, ch) in para.char_offsets.iter().zip(para.text.chars()) {
let units = offset
.checked_sub(end)
.filter(|units| units % 8 == 0)
.ok_or_else(invalid_raw_slots)?;
inner += (units / 8) as usize;
gaps.push((end, offset));
end = offset + if ch == '\t' { 8 } else { ch.len_utf16() as u32 };
}
let ranges = ¶.field_ranges;
let tail = (para.controls.len() + ranges.len())
.checked_sub(inner)
.ok_or_else(invalid_raw_slots)?;
gaps.push((end, end + 8 * tail as u32));
let mut slots = 0;
let mut placed = 0;
for (gap, &(start, end)) in gaps.iter().enumerate() {
slots += ((end - start) / 8) as usize;
let ends = ranges
.iter()
.filter(|range| range.end_char_idx <= gap)
.count();
let begun = ranges
.iter()
.filter(|range| range.start_char_idx <= gap)
.map(|range| range.control_idx + 1)
.max()
.unwrap_or(0);
let before_next = ranges
.iter()
.filter(|range| range.start_char_idx > gap)
.map(|range| range.control_idx)
.min()
.unwrap_or(para.controls.len());
placed = slots
.checked_sub(ends)
.filter(|&controls| controls >= placed && (begun..=before_next).contains(&controls))
.ok_or_else(invalid_raw_slots)?;
}
Ok(gaps)
}
pub(crate) fn json_escape(s: &str) -> String {
let mut result = String::with_capacity(s.len() + 2);
result.push('"');
for c in s.chars() {
match c {
'"' => result.push_str("\\\""),
'\\' => result.push_str("\\\\"),
'\n' => result.push_str("\\n"),
'\r' => result.push_str("\\r"),
'\t' => result.push_str("\\t"),
c if (c as u32) < 0x20 => {
result.push_str(&format!("\\u{:04x}", c as u32));
}
_ => result.push(c),
}
}
result.push('"');
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::control::{Control, Field, FieldType};
use crate::model::document::Section;
use crate::model::paragraph::{FieldRange, LineSeg, Paragraph};
use crate::model::table::{Cell, Table};
fn make_field_control(ctrl_id: u32) -> Control {
Control::Field(Field {
field_type: FieldType::ClickHere,
command: String::new(),
properties: 0,
extra_properties: 0,
field_id: ctrl_id,
ctrl_id,
instance_id: None,
raw_type: None,
ctrl_data_name: None,
memo_index: 0,
memo_paragraphs: Vec::new(),
memo_text_direction: None,
raw_parameters_xml: None,
parameters: Default::default(),
guide_residue: None,
hyperlink_format: None,
})
}
fn para_with_click_here_field() -> Paragraph {
Paragraph {
text: "ABCXY".into(),
controls: vec![
Control::ColumnDef(Default::default()),
make_field_control(100),
],
field_ranges: vec![FieldRange {
start_char_idx: 3,
end_char_idx: 5,
control_idx: 1,
..Default::default()
}],
char_count: 21,
char_offsets: vec![8, 9, 10, 19, 20],
..Default::default()
}
}
#[test]
fn tab_occupies_eight_stream_units() {
let para = Paragraph {
text: "AB\tCD".into(),
char_count: 13, ..Default::default()
};
assert_eq!(stream_pos(¶, 0), 0);
assert_eq!(stream_pos(¶, 2), 2, "탭 앞은 그대로다");
assert_eq!(stream_pos(¶, 3), 10, "탭 하나를 지나면 8칸");
assert_eq!(stream_pos(¶, 5), 12);
assert_eq!(stream_len(¶), 12);
assert_eq!(char_idx_at_stream_pos(¶, 10), 3);
assert_eq!(char_idx_at_stream_pos(¶, 12), 5);
}
#[test]
fn remove_field_at_invalidates_raw_stream() {
let mut core = DocumentCore::new_empty();
core.document.sections.push(Section {
paragraphs: vec![para_with_click_here_field()],
raw_stream: Some(vec![0xAB; 64]),
..Default::default()
});
core.composed = vec![Vec::new()];
core.dirty_sections = vec![true];
core.dirty_paragraphs = vec![None];
core.remove_field_at(0, 0, 4).unwrap();
assert!(
core.document.sections[0].raw_stream.is_none(),
"remove_field_at 후 raw_stream 이 무효화돼야 한다"
);
let bytes = crate::serializer::body_text::serialize_section(&core.document.sections[0]);
assert_ne!(
bytes,
vec![0xAB; 64],
"serialize_section 이 여전히 원본 바이트를 반환"
);
assert_eq!(core.document.sections[0].paragraphs[0].controls.len(), 1);
}
#[test]
fn remove_field_at_in_cell_invalidates_raw_stream() {
let table = Table {
cells: vec![Cell {
paragraphs: vec![para_with_click_here_field()],
..Default::default()
}],
..Default::default()
};
let parent_para = Paragraph {
controls: vec![Control::Table(Box::new(table))],
..Default::default()
};
let mut core = DocumentCore::new_empty();
core.document.sections.push(Section {
paragraphs: vec![parent_para],
raw_stream: Some(vec![0xAB; 64]),
..Default::default()
});
core.composed = vec![Vec::new()];
core.dirty_sections = vec![true];
core.dirty_paragraphs = vec![None];
core.remove_field_at_in_cell(0, 0, 0, 0, 0, 4, false)
.unwrap();
assert!(
core.document.sections[0].raw_stream.is_none(),
"remove_field_at_in_cell 후 raw_stream 이 무효화돼야 한다"
);
let bytes = crate::serializer::body_text::serialize_section(&core.document.sections[0]);
assert_ne!(bytes, vec![0xAB; 64]);
}
fn para_with_named_cells(names: &[&str]) -> Paragraph {
let table = Table {
cells: names
.iter()
.map(|name| Cell {
field_name: Some((*name).to_string()),
paragraphs: vec![Paragraph::default()],
..Default::default()
})
.collect(),
..Default::default()
};
Paragraph {
controls: vec![Control::Table(Box::new(table))],
..Default::default()
}
}
fn core_with(paragraphs: Vec<Paragraph>) -> DocumentCore {
let mut core = DocumentCore::new_empty();
core.document.sections.push(Section {
paragraphs,
raw_stream: Some(vec![0xAB; 64]),
..Default::default()
});
core.composed = vec![Vec::new()];
core.dirty_sections = vec![true];
core.dirty_paragraphs = vec![None];
core
}
fn field_names(core: &DocumentCore) -> Vec<String> {
core.collect_all_fields()
.iter()
.filter_map(|fi| fi.field.field_name().map(str::to_string))
.collect()
}
fn para_with_cells(cells: Vec<Cell>) -> Paragraph {
Paragraph {
controls: vec![Control::Table(Box::new(Table {
cells,
..Default::default()
}))],
..Default::default()
}
}
fn named_cell(name: &str, paragraphs: Vec<Paragraph>) -> Cell {
Cell {
field_name: Some(name.to_string()),
paragraphs,
..Default::default()
}
}
#[test]
fn list_ids_run_depth_first_from_two() {
let inner = para_with_cells(vec![
named_cell("inner0", vec![Paragraph::default()]),
named_cell("inner1", vec![Paragraph::default()]),
]);
let outer = para_with_cells(vec![
named_cell("outer0", vec![Paragraph::default()]),
named_cell("outer1", vec![inner]),
named_cell("outer2", vec![Paragraph::default()]),
]);
let core = core_with(vec![outer]);
let (fields, lists) = core.collect_fields_and_lists();
let ids: Vec<(String, u32)> = fields
.iter()
.map(|fi| (fi.field.field_name().unwrap_or("").to_string(), fi.list_id))
.collect();
assert_eq!(
ids,
vec![
("outer0".to_string(), 2),
("outer1".to_string(), 3),
("inner0".to_string(), 4),
("inner1".to_string(), 5),
("outer2".to_string(), 6),
],
"셀 3 다음에 그 안의 표가 오고, 그 뒤에 셀 6 이 이어져야 한다"
);
assert_eq!(lists.len(), 5);
assert_eq!(lists[2].host_list_id, 3);
assert_eq!(lists[0].host_list_id, ROOT_LIST_ID);
}
#[test]
fn cursor_model_top_pos_skips_anchored_controls() {
let mut anchored = para_with_cells(vec![named_cell("a", vec![Paragraph::default()])]);
anchored.char_count = 9;
let mut core = core_with(vec![anchored]);
let model = core.get_cursor_model_json();
assert!(
model.contains("\"topPos\":8"),
"자리차지 표 하나를 건너뛰어 8이어야 한다: {model}"
);
if let Control::Table(t) = &mut core.document.sections[0].paragraphs[0].controls[0] {
t.common.treat_as_char = true;
}
let model = core.get_cursor_model_json();
assert!(
model.contains("\"topPos\":0"),
"인라인 표 앞에서 멈춰 0이어야 한다: {model}"
);
}
#[test]
fn para_bounds_never_start_past_end() {
let mut anchored = para_with_cells(vec![named_cell("a", vec![Paragraph::default()])]);
anchored.char_count = 9;
let core = core_with(vec![anchored]);
let bounds = core.para_bounds_json(0, 0);
assert_eq!(
bounds, r#"{"start":8,"end":8,"selectStart":0}"#,
"시작이 끝을 넘으면 안 된다: {bounds}"
);
}
#[test]
fn rename_field_renames_cell_field() {
let mut core = core_with(vec![para_with_named_cells(&["pt_nm"])]);
let json = core.rename_field_by_name("pt_nm", "환자명").unwrap();
assert_eq!(json, r#"{"ok":true,"renamed":1}"#);
assert_eq!(field_names(&core), vec!["환자명".to_string()]);
assert!(
core.document.sections[0].raw_stream.is_none(),
"raw_stream 이 남으면 저장이 옛 이름을 재방출한다"
);
}
#[test]
fn rename_field_renames_every_occurrence() {
let mut core = core_with(vec![
para_with_named_cells(&["pt_no", "other"]),
para_with_named_cells(&["pt_no"]),
]);
let json = core.rename_field_by_name("pt_no", "접수번호").unwrap();
assert_eq!(json, r#"{"ok":true,"renamed":2}"#);
assert_eq!(
field_names(&core),
vec![
"접수번호".to_string(),
"other".to_string(),
"접수번호".to_string()
]
);
}
#[test]
fn rename_field_rewrites_click_here_ctrl_data() {
let mut para = para_with_click_here_field();
if let Control::Field(f) = &mut para.controls[1] {
f.ctrl_data_name = Some("old_name".into());
}
let mut core = core_with(vec![para]);
let json = core.rename_field_by_name("old_name", "새이름").unwrap();
assert_eq!(json, r#"{"ok":true,"renamed":1}"#);
assert_eq!(field_names(&core), vec!["새이름".to_string()]);
let record = core.document.sections[0].paragraphs[0].ctrl_data_records[1]
.as_ref()
.expect("CTRL_DATA 레코드가 만들어져야 한다");
let name_len = u16::from_le_bytes([record[10], record[11]]) as usize;
let chars: Vec<u16> = record[12..12 + name_len * 2]
.chunks_exact(2)
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
assert_eq!(String::from_utf16_lossy(&chars), "새이름");
}
#[test]
fn rename_field_missing_name_changes_nothing() {
let mut core = core_with(vec![para_with_named_cells(&["pt_nm"])]);
let json = core.rename_field_by_name("없는필드", "아무개").unwrap();
assert_eq!(json, r#"{"ok":false,"renamed":0}"#);
assert_eq!(field_names(&core), vec!["pt_nm".to_string()]);
assert!(
core.document.sections[0].raw_stream.is_some(),
"바꾼 게 없으면 원본 스트림을 버리지 않는다"
);
}
#[test]
fn set_cell_field_text_updates_text_metadata() {
modest_cell_field_fill_reaches_frame_consumers_before_serialization();
let cell_para = Paragraph {
text: "기존값".into(),
char_count: 4,
char_offsets: vec![0, 1, 2],
..Default::default()
};
let table = Table {
cells: vec![Cell {
field_name: Some("셀필드".into()),
paragraphs: vec![cell_para],
..Default::default()
}],
..Default::default()
};
let parent_para = Paragraph {
controls: vec![Control::Table(Box::new(table))],
..Default::default()
};
let mut core = DocumentCore::new_empty();
core.document.sections.push(Section {
paragraphs: vec![parent_para],
..Default::default()
});
let location = FieldLocation {
section_index: 0,
para_index: 0,
nested_path: vec![NestedEntry::TableCell {
control_index: 0,
cell_index: 0,
para_index: 0,
}],
};
core.set_cell_field_text(&location, "새값").unwrap();
let Control::Table(table) = &core.document.sections[0].paragraphs[0].controls[0] else {
panic!("expected table control");
};
let updated = &table.cells[0].paragraphs[0];
assert_eq!(updated.text, "새값");
assert_eq!(updated.char_count, 3);
assert_eq!(updated.char_offsets, vec![0, 1]);
}
fn modest_cell_field_fill_reaches_frame_consumers_before_serialization() {
let initial = "old";
let cell_para = Paragraph {
text: initial.into(),
char_count: 4,
char_offsets: vec![0, 1, 2],
line_segs: vec![LineSeg {
text_start: 0,
line_height: 1_000,
text_height: 900,
baseline_distance: 800,
segment_width: 1,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..Default::default()
}],
..Default::default()
};
let mut core = DocumentCore::new_empty();
core.document.sections.push(Section {
paragraphs: vec![Paragraph {
controls: vec![Control::Table(Box::new(Table {
cells: vec![Cell {
field_name: Some("셀필드".into()),
paragraphs: vec![cell_para],
..Default::default()
}],
..Default::default()
}))],
..Default::default()
}],
..Default::default()
});
let location = FieldLocation {
section_index: 0,
para_index: 0,
nested_path: vec![NestedEntry::TableCell {
control_index: 0,
cell_index: 0,
para_index: 0,
}],
};
core.set_cell_field_text(&location, "moderately wider field value")
.unwrap();
let styles = crate::renderer::style_resolver::ResolvedStyleSet::default();
let dpi = 96.0;
let measured = {
let Control::Table(table) = &core.document.sections[0].paragraphs[0].controls[0] else {
panic!("expected table control");
};
let para = &table.cells[0].paragraphs[0];
assert!(para.line_segs.is_empty());
let composed = crate::renderer::composer::compose_paragraph(para);
crate::renderer::composer::estimate_composed_line_width(&composed.lines[0], &styles)
};
let width_hwp = crate::renderer::px_to_hwpunit(measured / 1.2, dpi);
let inner_width = crate::renderer::hwpunit_to_px(width_hwp, dpi);
assert!(measured > inner_width && measured < inner_width * 1.8);
let Control::Table(table) = &core.document.sections[0].paragraphs[0].controls[0] else {
panic!("expected table control");
};
let para = &table.cells[0].paragraphs[0];
let mut composed = crate::renderer::composer::compose_paragraph(para);
crate::renderer::composer::recompose_cell_lines_in_frame(
&mut composed,
para,
crate::renderer::composer::ParagraphBox::content(0..width_hwp),
&styles,
dpi,
false,
);
assert!(
composed.lines.len() > 1,
"the shared cell consumer must see a fresh boundary before save/reload"
);
assert!(composed.lines[1].char_start > 0);
}
}