use super::MIN_SHAPE_SIZE;
use crate::document_core::helpers::{get_textbox_at, get_textbox_at_mut};
use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;
use crate::model::paragraph::Paragraph;
use crate::model::shape::common_obj_offsets;
use crate::renderer::render_tree::{RenderNode, RenderNodeType};
mod creation_line;
const INLINE_TABLE_OUTER_MARGIN: i16 = 283;
#[derive(Clone, Copy)]
enum InlineTableAnchor {
Body,
Cell,
}
impl InlineTableAnchor {
fn rel(
self,
) -> (
u32,
crate::model::shape::VertRelTo,
crate::model::shape::HorzRelTo,
) {
use crate::model::shape::{HorzRelTo, VertRelTo};
match self {
#[allow(clippy::identity_op)]
InlineTableAnchor::Body => ((0 << 3) | (3 << 8), VertRelTo::Page, HorzRelTo::Para),
InlineTableAnchor::Cell => ((2 << 3) | (2 << 8), VertRelTo::Para, HorzRelTo::Column),
}
}
}
fn find_table_cells(
node: &RenderNode,
sec: usize,
ppi: usize,
ci: usize,
page_idx: usize,
result: &mut Vec<String>,
) -> bool {
if let RenderNodeType::Table(ref tn) = node.node_type {
if tn.section_index == Some(sec)
&& tn.para_index == Some(ppi)
&& tn.control_index == Some(ci)
{
for child in &node.children {
if let RenderNodeType::TableCell(ref cn) = child.node_type {
let model_cell_idx = cn.model_cell_index.unwrap_or(0) as usize;
result.push(format!(
"{{\"cellIdx\":{},\"row\":{},\"col\":{},\"rowSpan\":{},\"colSpan\":{},\"pageIndex\":{},\"x\":{:.1},\"y\":{:.1},\"w\":{:.1},\"h\":{:.1}}}",
model_cell_idx, cn.row, cn.col, cn.row_span, cn.col_span,
page_idx,
child.bbox.x, child.bbox.y, child.bbox.width, child.bbox.height
));
}
}
return true; }
}
for child in &node.children {
if find_table_cells(child, sec, ppi, ci, page_idx, result) {
return true;
}
}
false
}
impl DocumentCore {
fn parse_cell_path_json(json: &str) -> Result<Vec<(usize, usize, usize)>, HwpError> {
let path: Vec<(usize, usize, usize)> = serde_json::from_str::<Vec<serde_json::Value>>(json)
.map_err(|e| HwpError::RenderError(format!("cell_path JSON 파싱 실패: {}", e)))?
.iter()
.map(|v| {
let c = v
.get("controlIdx")
.or_else(|| v.get("controlIndex"))
.and_then(|x| x.as_u64())
.unwrap_or(0) as usize;
let ci = v
.get("cellIdx")
.or_else(|| v.get("cellIndex"))
.and_then(|x| x.as_u64())
.unwrap_or(0) as usize;
let cpi = v
.get("cellParaIdx")
.or_else(|| v.get("cellParaIndex"))
.and_then(|x| x.as_u64())
.unwrap_or(0) as usize;
(c, ci, cpi)
})
.collect();
if path.is_empty() {
return Err(HwpError::RenderError(
"cell_path 가 비어있습니다".to_string(),
));
}
Ok(path)
}
pub(crate) fn resolve_cell_paragraph_mut<'a>(
section: &'a mut crate::model::document::Section,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
) -> Result<&'a mut crate::model::paragraph::Paragraph, HwpError> {
let mut current_para = section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
for (i, &(ctrl_idx, cell_idx, cell_para_idx)) in path.iter().enumerate() {
let ctrl = current_para.controls.get_mut(ctrl_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[{}]: controls[{}] 범위 초과", i, ctrl_idx))
})?;
current_para = match ctrl {
crate::model::control::Control::Table(t) => {
let cell = t.cells.get_mut(cell_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[{}]: cells[{}] 범위 초과", i, cell_idx))
})?;
cell.paragraphs.get_mut(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: paragraphs[{}] 범위 초과",
i, cell_para_idx
))
})?
}
crate::model::control::Control::Shape(shape) => {
let text_box = get_textbox_at_mut(shape, cell_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: controls[{}]가 텍스트 글상자가 아닙니다",
i, ctrl_idx
))
})?;
text_box.paragraphs.get_mut(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: 글상자문단 {} 범위 초과",
i, cell_para_idx
))
})?
}
crate::model::control::Control::Picture(pic) => {
if cell_idx != 0 {
return Err(HwpError::RenderError(format!(
"경로[{}]: 그림 캡션의 cell_index는 0이어야 합니다 ({})",
i, cell_idx
)));
}
let caption = pic.caption.as_mut().ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: controls[{}] 그림에 캡션이 없습니다",
i, ctrl_idx
))
})?;
caption.paragraphs.get_mut(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: 그림 캡션문단 {} 범위 초과",
i, cell_para_idx
))
})?
}
ctrl @ (crate::model::control::Control::Header(_)
| crate::model::control::Control::Footer(_)) => {
if cell_idx != 0 {
return Err(HwpError::RenderError(format!(
"경로[{}]: 머리말·꼬리말의 cell_index는 0이어야 합니다 ({})",
i, cell_idx
)));
}
ctrl.header_footer_paragraphs_mut()
.and_then(|paragraphs| paragraphs.get_mut(cell_para_idx))
.ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: 머리말·꼬리말 문단 {} 범위 초과",
i, cell_para_idx
))
})?
}
_ => {
return Err(HwpError::RenderError(format!(
"경로[{}]: controls[{}] 가 표/글상자/그림 캡션이 아닙니다",
i, ctrl_idx
)))
}
};
}
Ok(current_para)
}
fn required_cell_height_for_picture(
cell: &crate::model::table::Cell,
pic: &crate::model::image::Picture,
) -> u32 {
Self::required_cell_height_for_picture_padding(cell.padding.top, cell.padding.bottom, pic)
}
fn required_cell_height_for_picture_padding(
padding_top: i16,
padding_bottom: i16,
pic: &crate::model::image::Picture,
) -> u32 {
let vert_offset = (pic.common.vertical_offset as i32).max(0) as u32;
let visual_height = if pic.shape_attr.rotation_angle.rem_euclid(360) != 0
&& pic.shape_attr.current_width > 0
&& pic.shape_attr.current_height > 0
{
pic.common.height
} else {
let (_, height) = Self::picture_rotated_bounds(
pic.common.width,
pic.common.height,
pic.shape_attr.rotation_angle,
);
height
};
vert_offset
.saturating_add(visual_height)
.saturating_add(padding_top.max(0) as u32)
.saturating_add(padding_bottom.max(0) as u32)
}
fn sync_direct_owner_cell_for_picture(
section: &mut crate::model::document::Section,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
inner_control_idx: usize,
) -> Result<(), HwpError> {
if path.len() != 1 {
return Ok(());
}
let (table_ctrl_idx, cell_idx, cell_para_idx) = path[0];
let para = section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
let existing_line_height = para
.line_segs
.first()
.map(|seg| seg.line_height)
.unwrap_or(0);
let table = match para.controls.get_mut(table_ctrl_idx) {
Some(Control::Table(table)) => table,
_ => return Ok(()),
};
let line_height_extra = (existing_line_height - table.common.height as i32).max(0);
let mut line_seg_update: Option<(i32, i32)> = None;
let required_height = {
let cell = table.cells.get(cell_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[0]: cells[{}] 범위 초과", cell_idx))
})?;
let cell_para = cell.paragraphs.get(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[0]: paragraphs[{}] 범위 초과", cell_para_idx))
})?;
let pic = match cell_para.controls.get(inner_control_idx) {
Some(Control::Picture(pic)) => pic,
_ => return Ok(()),
};
let take_place_flow_offset = Self::take_place_picture_flow_offset(pic);
if table.common.treat_as_char {
if let Some(flow_offset) = take_place_flow_offset {
let vertical_pos = if pic.common.flow_with_text {
0
} else {
flow_offset
};
line_seg_update = Some((vertical_pos, line_height_extra));
}
}
if pic.common.flow_with_text {
Some(Self::required_cell_height_for_picture(cell, pic))
} else {
None
}
};
if let (Some(required_height), Some(cell)) =
(required_height, table.cells.get_mut(cell_idx))
{
let synced_height = required_height.max(MIN_SHAPE_SIZE);
if cell.height != synced_height {
cell.height = synced_height;
}
}
table.update_ctrl_dimensions();
let new_table_height = table.common.height as i32;
if let Some((vertical_pos, line_height_extra)) = line_seg_update {
if let Some(seg) = para.line_segs.first_mut() {
let line_height = new_table_height
.saturating_add(line_height_extra)
.max(MIN_SHAPE_SIZE as i32);
seg.vertical_pos = vertical_pos;
seg.line_height = line_height;
seg.text_height = line_height;
seg.baseline_distance =
((line_height as i64 * 17 + 10) / 20).min(i32::MAX as i64) as i32;
}
}
Ok(())
}
fn clamp_direct_owner_cell_picture_offsets(
section: &mut crate::model::document::Section,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
inner_control_idx: usize,
clamp_horz: bool,
clamp_vert: bool,
) -> Result<(), HwpError> {
if path.len() != 1 || (!clamp_horz && !clamp_vert) {
return Ok(());
}
let (table_ctrl_idx, cell_idx, cell_para_idx) = path[0];
let para = section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
let table = match para.controls.get_mut(table_ctrl_idx) {
Some(Control::Table(table)) => table,
_ => return Ok(()),
};
let cell = table.cells.get_mut(cell_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[0]: cells[{}] 범위 초과", cell_idx))
})?;
let inner_width = cell
.width
.saturating_sub(cell.padding.left.max(0) as u32)
.saturating_sub(cell.padding.right.max(0) as u32) as i64;
let cell_para = cell.paragraphs.get_mut(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[0]: paragraphs[{}] 범위 초과", cell_para_idx))
})?;
let pic = match cell_para.controls.get_mut(inner_control_idx) {
Some(Control::Picture(pic)) => pic,
_ => return Ok(()),
};
if !pic.common.flow_with_text {
return Ok(());
}
if clamp_horz {
let max_horz = (inner_width - pic.common.width as i64)
.max(0)
.min(i32::MAX as i64);
let horz = (pic.common.horizontal_offset as i32).clamp(0, max_horz as i32);
pic.common.horizontal_offset = horz as u32;
}
if clamp_vert {
let vert = (pic.common.vertical_offset as i32).max(0);
pic.common.vertical_offset = vert as u32;
}
Ok(())
}
pub(crate) fn cell_path_terminates_at_textbox(
section: &crate::model::document::Section,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
) -> Result<bool, HwpError> {
let mut current_para = section.paragraphs.get(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
for (i, &(ctrl_idx, cell_idx, cell_para_idx)) in path.iter().enumerate() {
let ctrl = current_para.controls.get(ctrl_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[{}]: controls[{}] 범위 초과", i, ctrl_idx))
})?;
match ctrl {
crate::model::control::Control::Table(table) => {
let cell = table.cells.get(cell_idx).ok_or_else(|| {
HwpError::RenderError(format!("경로[{}]: cells[{}] 범위 초과", i, cell_idx))
})?;
if i == path.len() - 1 {
return Ok(false);
}
current_para = cell.paragraphs.get(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: paragraphs[{}] 범위 초과",
i, cell_para_idx
))
})?;
}
crate::model::control::Control::Shape(shape) => {
let text_box = get_textbox_at(shape.as_ref(), cell_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: controls[{}]가 텍스트 글상자가 아닙니다",
i, ctrl_idx
))
})?;
if i == path.len() - 1 {
return Ok(true);
}
current_para = text_box.paragraphs.get(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!(
"경로[{}]: 글상자문단 {} 범위 초과",
i, cell_para_idx
))
})?;
}
_ => {
return Err(HwpError::RenderError(format!(
"경로[{}]: controls[{}] 가 표/글상자가 아닙니다",
i, ctrl_idx
)))
}
}
}
Err(HwpError::RenderError("경로가 비어있습니다".to_string()))
}
pub fn create_table_native(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
row_count: u16,
col_count: u16,
) -> Result<String, HwpError> {
self.create_table_with_options_native(
section_idx,
para_idx,
char_offset,
row_count,
col_count,
&super::TableCreationOptions::default(),
)
}
pub fn create_table_with_options_native(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
row_count: u16,
col_count: u16,
options: &super::TableCreationOptions,
) -> Result<String, HwpError> {
use crate::model::paragraph::{CharShapeRef, LineSeg};
use crate::model::style::{
BorderFill, BorderLine, BorderLineType, CenterLine, DiagonalLine, Fill,
};
use crate::model::table::{Cell, Table, TablePageBreak};
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과 (총 {}개)",
section_idx,
self.document.sections.len()
)));
}
if para_idx >= self.document.sections[section_idx].paragraphs.len() {
return Err(HwpError::RenderError(format!(
"문단 인덱스 {} 범위 초과",
para_idx
)));
}
if row_count == 0 || col_count == 0 || col_count > 256 {
return Err(HwpError::RenderError(format!(
"행/열 수 범위 오류 (행={}, 열={}, 열은 1~256)",
row_count, col_count
)));
}
let instance_id = super::super::clone_identity::next_instance_id(&self.document)?;
let pd = &self.document.sections[section_idx].section_def.page_def;
let outer_margin_lr: i32 = 283 * 2; let content_width =
(pd.width as i32 - pd.margin_left as i32 - pd.margin_right as i32 - outer_margin_lr)
.max(7200) as u32;
let col_widths = options
.widths(col_count, content_width)
.map_err(HwpError::RenderError)?;
let cell_pad = crate::model::Padding {
left: 510,
right: 510,
top: 141,
bottom: 141,
};
let cell_height: u32 = (cell_pad.top + cell_pad.bottom) as u32;
let inherited_line = creation_line::for_cursor(self, section_idx, para_idx, char_offset);
let rendered_row_height: u32 =
cell_pad.top as u32 + inherited_line.line_height.max(0) as u32 + cell_pad.bottom as u32;
let total_width: u32 = col_widths.iter().sum();
let total_height = rendered_row_height * row_count as u32;
let cell_border_fill_id = {
let existing = self.document.doc_info.border_fills.iter().position(|bf| {
bf.borders
.iter()
.all(|b| b.line_type == BorderLineType::Solid && b.width >= 1)
});
if let Some(idx) = existing {
(idx + 1) as u16 } else {
let solid_border = BorderLine {
line_type: BorderLineType::Solid,
width: 1,
color: 0,
};
let new_bf = BorderFill {
raw_data: None,
attr: 0,
borders: [solid_border, solid_border, solid_border, solid_border],
diagonal: DiagonalLine {
diagonal_type: 1,
width: 0,
color: 0,
},
center_line: CenterLine::None,
fill: Fill::default(),
three_d: false,
break_cell_separate_line: false,
};
self.document.doc_info.border_fills.push(new_bf);
self.document.doc_info.raw_stream = None;
self.document.doc_info.border_fills.len() as u16 }
};
let current_para = &self.document.sections[section_idx].paragraphs[para_idx];
let default_char_shape_id: u32 = current_para.char_shape_id_at(char_offset).unwrap_or(0);
let default_para_shape_id: u16 = current_para.para_shape_id;
let para_shape_ids: Vec<u16> = (0..col_count)
.map(|col| {
options
.column_alignments
.as_ref()
.map_or(default_para_shape_id, |alignments| {
self.document.find_or_create_para_shape(
default_para_shape_id,
&crate::model::style::ParaShapeMods {
alignment: Some(alignments[usize::from(col)]),
..Default::default()
},
)
})
})
.collect();
let mut cells = Vec::with_capacity((row_count as usize) * (col_count as usize));
for r in 0..row_count {
for c in 0..col_count {
let col_width = col_widths[usize::from(c)];
let mut cell = Cell::new_empty(c, r, col_width, cell_height, cell_border_fill_id);
if options.repeat_header.is_some() {
cell.set_header(r == 0 && options.repeat_header == Some(true));
}
cell.padding = cell_pad;
cell.vertical_align = crate::model::table::VerticalAlign::Center; for cp in &mut cell.paragraphs {
cp.char_count_msb = true;
cp.para_shape_id = para_shape_ids[usize::from(c)];
cp.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: default_char_shape_id,
}];
if cp.raw_header_extra.len() < 10 {
let mut rhe = vec![0u8; 10];
rhe[0..2].copy_from_slice(&1u16.to_le_bytes()); rhe[4..6].copy_from_slice(&1u16.to_le_bytes()); cp.raw_header_extra = rhe;
}
let seg_w = (col_width as i32) - 141 - 141; cp.line_segs = vec![LineSeg {
segment_width: seg_w,
..inherited_line.clone()
}];
}
cell.raw_list_extra = Vec::new();
cells.push(cell);
}
}
let row_sizes: Vec<i16> = (0..row_count).map(|_| col_count as i16).collect();
let flags: u32 = (2 << 3) | (3 << 8) | (4 << 15) | (2 << 18) | (1 << 21) | (2 << 26);
let outer_margin: i16 = 283; let mut raw_ctrl_data = vec![0u8; 38];
raw_ctrl_data[common_obj_offsets::FLAGS].copy_from_slice(&flags.to_le_bytes());
raw_ctrl_data[common_obj_offsets::WIDTH].copy_from_slice(&total_width.to_le_bytes());
raw_ctrl_data[common_obj_offsets::HEIGHT].copy_from_slice(&total_height.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_LEFT].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_RIGHT]
.copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_TOP].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_BOTTOM]
.copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::INSTANCE_ID].copy_from_slice(&instance_id.to_le_bytes());
let mut table = Table {
attr: 0x082A2210, row_count,
col_count,
cell_spacing: 0,
padding: crate::model::Padding {
left: 510,
right: 510,
top: 141,
bottom: 141,
},
row_sizes,
border_fill_id: cell_border_fill_id, zones: Vec::new(),
cells,
cell_grid: Vec::new(),
page_break: if options.repeat_header.is_some() {
TablePageBreak::RowBreak
} else {
TablePageBreak::None
},
repeat_header: options.repeat_header.unwrap_or(false),
caption: None,
common: crate::model::shape::CommonObjAttr {
attr: flags,
numbering_type: crate::model::shape::ObjectNumberingType::Table,
margin: crate::model::Padding {
left: outer_margin,
right: outer_margin,
top: outer_margin,
bottom: outer_margin,
},
instance_id,
treat_as_char: false,
text_wrap: crate::model::shape::TextWrap::TopAndBottom,
vert_rel_to: crate::model::shape::VertRelTo::Para,
horz_rel_to: crate::model::shape::HorzRelTo::Para,
vert_align: crate::model::shape::VertAlign::Top,
horz_align: crate::model::shape::HorzAlign::Left,
width: total_width,
height: total_height,
..Default::default()
},
outer_margin_left: 283,
outer_margin_right: 283,
outer_margin_top: 283,
outer_margin_bottom: 283,
raw_ctrl_data,
raw_ctrl_seal: None,
raw_table_record_attr: options.repeat_header.map_or(0x00000006, |repeat| {
2 | (u32::from(repeat) << 2) }),
raw_table_record_extra: Vec::new(),
layout_page_break_cache: Default::default(),
};
table.rebuild_grid();
let table_para_shape_id = default_para_shape_id;
let mut table_raw_header_extra = vec![0u8; 10];
table_raw_header_extra[0..2].copy_from_slice(&1u16.to_le_bytes());
table_raw_header_extra[4..6].copy_from_slice(&1u16.to_le_bytes());
let mut table_para = Paragraph {
text: String::new(),
char_count: 9, control_mask: 0x00000800,
char_offsets: vec![],
char_shapes: vec![CharShapeRef {
start_pos: 0,
char_shape_id: default_char_shape_id,
}],
line_segs: vec![LineSeg {
segment_width: 0, ..inherited_line.clone()
}],
para_shape_id: table_para_shape_id,
style_id: 0,
controls: vec![Control::Table(Box::new(table))],
ctrl_data_records: vec![None],
has_para_text: true,
raw_header_extra: table_raw_header_extra,
char_count_msb: false,
..Default::default()
};
let make_empty_neighbor_para = || {
let mut empty_raw_header_extra = vec![0u8; 10];
empty_raw_header_extra[0..2].copy_from_slice(&1u16.to_le_bytes());
empty_raw_header_extra[4..6].copy_from_slice(&1u16.to_le_bytes());
Paragraph {
text: String::new(),
char_count: 1,
char_count_msb: false,
control_mask: 0,
para_shape_id: default_para_shape_id,
style_id: 0,
char_shapes: vec![CharShapeRef {
start_pos: 0,
char_shape_id: default_char_shape_id,
}],
line_segs: vec![LineSeg {
segment_width: content_width as i32,
..inherited_line.clone()
}],
has_para_text: false,
raw_header_extra: empty_raw_header_extra,
..Default::default()
}
};
self.document.sections[section_idx].raw_stream = None;
let para = &self.document.sections[section_idx].paragraphs[para_idx];
let is_empty_para = para.text.is_empty() && para.controls.is_empty();
let is_structure_only_empty_para = Self::is_structure_only_empty_paragraph(para);
let insert_para_idx;
let table_control_idx;
let mut did_split_for_table = false;
if is_empty_para {
table_para.column_type = para.column_type;
table_para.raw_break_type = para.raw_break_type;
table_para.page_break_synthesized = para.page_break_synthesized;
self.document.sections[section_idx].paragraphs[para_idx] = table_para;
insert_para_idx = para_idx;
table_control_idx = 0;
} else if is_structure_only_empty_para {
let old_para = self.document.sections[section_idx].paragraphs[para_idx].clone();
let mut merged_para = table_para;
let table_control = merged_para
.controls
.pop()
.ok_or_else(|| HwpError::RenderError("표 컨트롤 생성 실패".to_string()))?;
let table_ctrl_data = merged_para.ctrl_data_records.pop().unwrap_or(None);
merged_para.controls = old_para.controls;
merged_para.ctrl_data_records = old_para.ctrl_data_records;
while merged_para.ctrl_data_records.len() < merged_para.controls.len() {
merged_para.ctrl_data_records.push(None);
}
table_control_idx = merged_para.controls.len();
merged_para.controls.push(table_control);
merged_para.ctrl_data_records.push(table_ctrl_data);
merged_para.char_count = merged_para.controls.len() as u32 * 8 + 1;
merged_para.control_mask = old_para.control_mask | 0x0000_0800;
merged_para.has_para_text = true;
self.document.sections[section_idx].paragraphs[para_idx] = merged_para;
insert_para_idx = para_idx;
} else if char_offset == 0 && para.controls.is_empty() {
self.document.sections[section_idx]
.paragraphs
.insert(para_idx, table_para);
if let Some(measured) = self.measured_sections.get_mut(section_idx) {
measured.shift_for_insert(para_idx);
}
insert_para_idx = para_idx;
table_control_idx = 0;
} else {
if char_offset > 0 && !para.text.is_empty() {
did_split_for_table = true;
let new_para =
self.document.sections[section_idx].paragraphs[para_idx].split_at(char_offset);
self.document.sections[section_idx]
.paragraphs
.insert(para_idx + 1, new_para);
if let Some(measured) = self.measured_sections.get_mut(section_idx) {
measured.shift_for_insert(para_idx + 1);
}
self.document.sections[section_idx]
.paragraphs
.insert(para_idx + 1, table_para);
if let Some(measured) = self.measured_sections.get_mut(section_idx) {
measured.shift_for_insert(para_idx + 1);
}
insert_para_idx = para_idx + 1;
table_control_idx = 0;
} else {
self.document.sections[section_idx]
.paragraphs
.insert(para_idx + 1, table_para);
if let Some(measured) = self.measured_sections.get_mut(section_idx) {
measured.shift_for_insert(para_idx + 1);
}
insert_para_idx = para_idx + 1;
table_control_idx = 0;
}
}
self.document.sections[section_idx]
.paragraphs
.insert(insert_para_idx + 1, make_empty_neighbor_para());
if let Some(measured) = self.measured_sections.get_mut(section_idx) {
measured.shift_for_insert(insert_para_idx + 1);
}
let fresh_end = insert_para_idx + 2 + usize::from(did_split_for_table);
for i in para_idx..fresh_end.min(self.document.sections[section_idx].paragraphs.len()) {
self.reflow_paragraph(section_idx, i);
}
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,
Some(insert_para_idx..fresh_end),
None,
&self.styles,
self.dpi,
doc_hwp3_layout,
);
self.rebuild_section(section_idx);
self.event_log.push(DocumentEvent::TableRowInserted {
section: section_idx,
para: insert_para_idx,
ctrl: table_control_idx,
});
Ok(crate::document_core::helpers::json_ok_with(&format!(
"\"paraIdx\":{},\"controlIdx\":{}",
insert_para_idx, table_control_idx
)))
}
#[allow(clippy::too_many_arguments)]
fn build_inline_table(
&mut self,
content_width: u32,
row_count: u16,
col_count: u16,
col_widths_hu: Option<&[u32]>,
row_heights_hu: Option<&[u32]>,
default_char_shape_id: u32,
default_para_shape_id: u16,
inherited_line: crate::model::paragraph::LineSeg,
anchor: InlineTableAnchor,
) -> Result<(crate::model::table::Table, bool), HwpError> {
use crate::model::paragraph::{CharShapeRef, LineSeg};
use crate::model::style::{
BorderFill, BorderLine, BorderLineType, CenterLine, DiagonalLine, Fill,
};
use crate::model::table::{Cell, Table, TablePageBreak};
let border_fills_before = self.document.doc_info.border_fills.len();
let instance_id = super::super::clone_identity::next_instance_id(&self.document)?;
let outer_margin: i16 = INLINE_TABLE_OUTER_MARGIN;
let col_ws: Vec<u32> = if let Some(widths) = col_widths_hu {
if widths.len() == col_count as usize {
widths.to_vec()
} else {
let w = content_width / col_count as u32;
vec![w; col_count as usize]
}
} else {
let w = content_width / col_count as u32;
vec![w; col_count as usize]
};
let total_width: u32 = col_ws.iter().sum();
let cell_pad = crate::model::Padding {
left: 510,
right: 510,
top: 141,
bottom: 141,
};
let min_row_height: u32 =
cell_pad.top as u32 + inherited_line.line_height.max(0) as u32 + cell_pad.bottom as u32;
let row_heights: Vec<u32> = if let Some(heights) = row_heights_hu {
if heights.len() == row_count as usize {
heights.iter().map(|h| (*h).max(min_row_height)).collect()
} else {
vec![min_row_height; row_count as usize]
}
} else {
vec![min_row_height; row_count as usize]
};
let total_height: u32 = row_heights.iter().sum();
let cell_border_fill_id = {
let existing = self.document.doc_info.border_fills.iter().position(|bf| {
bf.borders
.iter()
.all(|b| b.line_type == BorderLineType::Solid && b.width >= 1)
});
if let Some(idx) = existing {
(idx + 1) as u16
} else {
let solid_border = BorderLine {
line_type: BorderLineType::Solid,
width: 1,
color: 0,
};
let new_bf = BorderFill {
raw_data: None,
attr: 0,
borders: [solid_border, solid_border, solid_border, solid_border],
diagonal: DiagonalLine {
diagonal_type: 1,
width: 0,
color: 0,
},
center_line: CenterLine::None,
fill: Fill::default(),
three_d: false,
break_cell_separate_line: false,
};
self.document.doc_info.border_fills.push(new_bf);
self.document.doc_info.raw_stream = None;
self.document.doc_info.border_fills.len() as u16
}
};
let mut cells = Vec::with_capacity((row_count as usize) * (col_count as usize));
for r in 0..row_count {
let row_height = row_heights[r as usize];
for c in 0..col_count {
let col_w = col_ws[c as usize];
let mut cell = Cell::new_empty(c, r, col_w, row_height, cell_border_fill_id);
cell.padding = cell_pad;
cell.vertical_align = crate::model::table::VerticalAlign::Center;
for cp in &mut cell.paragraphs {
cp.char_count_msb = true;
cp.para_shape_id = default_para_shape_id;
cp.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: default_char_shape_id,
}];
if cp.raw_header_extra.len() < 10 {
let mut rhe = vec![0u8; 10];
rhe[0..2].copy_from_slice(&1u16.to_le_bytes());
rhe[4..6].copy_from_slice(&1u16.to_le_bytes());
cp.raw_header_extra = rhe;
}
let seg_w = (col_w as i32) - 141 - 141;
cp.line_segs = vec![LineSeg {
segment_width: seg_w,
..inherited_line.clone()
}];
}
cell.raw_list_extra = Vec::new();
cells.push(cell);
}
}
let row_sizes: Vec<i16> = (0..row_count).map(|_| col_count as i16).collect();
let (rel_bits, vert_rel_to, horz_rel_to) = anchor.rel();
#[allow(clippy::identity_op)]
let flags: u32 = (1 << 0)
| rel_bits
| (1 << 13)
| (4 << 15)
| (2 << 18)
| (1 << 21)
| (2 << 26) ;
let mut raw_ctrl_data = vec![0u8; 38];
raw_ctrl_data[common_obj_offsets::FLAGS].copy_from_slice(&flags.to_le_bytes());
raw_ctrl_data[common_obj_offsets::WIDTH].copy_from_slice(&total_width.to_le_bytes());
raw_ctrl_data[common_obj_offsets::HEIGHT].copy_from_slice(&total_height.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_LEFT].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_RIGHT]
.copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_TOP].copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::MARGIN_BOTTOM]
.copy_from_slice(&outer_margin.to_le_bytes());
raw_ctrl_data[common_obj_offsets::INSTANCE_ID].copy_from_slice(&instance_id.to_le_bytes());
let mut table = Table {
attr: flags,
row_count,
col_count,
cell_spacing: 0,
padding: cell_pad,
row_sizes,
border_fill_id: cell_border_fill_id,
zones: Vec::new(),
cells,
cell_grid: Vec::new(),
page_break: TablePageBreak::RowBreak,
repeat_header: false,
caption: None,
common: crate::model::shape::CommonObjAttr {
attr: flags,
numbering_type: crate::model::shape::ObjectNumberingType::Table,
margin: crate::model::Padding {
left: outer_margin,
right: outer_margin,
top: outer_margin,
bottom: outer_margin,
},
instance_id,
treat_as_char: true,
flow_with_text: true,
text_wrap: crate::model::shape::TextWrap::TopAndBottom,
vert_rel_to,
horz_rel_to,
vert_align: crate::model::shape::VertAlign::Top,
horz_align: crate::model::shape::HorzAlign::Left,
width: total_width,
height: total_height,
..Default::default()
},
outer_margin_left: outer_margin,
outer_margin_right: outer_margin,
outer_margin_top: outer_margin,
outer_margin_bottom: outer_margin,
raw_ctrl_data,
raw_ctrl_seal: None,
raw_table_record_attr: 0x04000006,
raw_table_record_extra: Vec::new(),
layout_page_break_cache: Default::default(),
};
table.rebuild_grid();
let added_border_fill = self.document.doc_info.border_fills.len() != border_fills_before;
Ok((table, added_border_fill))
}
pub fn create_table_ex_native(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
row_count: u16,
col_count: u16,
treat_as_char: bool,
col_widths_hu: Option<&[u32]>,
row_heights_hu: Option<&[u32]>,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과",
section_idx
)));
}
if para_idx >= self.document.sections[section_idx].paragraphs.len() {
return Err(HwpError::RenderError(format!(
"문단 인덱스 {} 범위 초과",
para_idx
)));
}
if row_count == 0 || col_count == 0 || col_count > 256 {
return Err(HwpError::RenderError(format!(
"행/열 수 범위 오류 (행={}, 열={})",
row_count, col_count
)));
}
if !treat_as_char {
return self.create_table_native(
section_idx,
para_idx,
char_offset,
row_count,
col_count,
);
}
let previous_host_end = crate::renderer::composer::paragraph_flow_end(
&self.document.sections[section_idx].paragraphs[para_idx],
);
let pd = &self.document.sections[section_idx].section_def.page_def;
let outer_margin: i16 = INLINE_TABLE_OUTER_MARGIN;
let outer_margin_lr = (outer_margin * 2) as i32;
let content_width =
(pd.width as i32 - pd.margin_left as i32 - pd.margin_right as i32 - outer_margin_lr)
.max(7200) as u32;
let current_para = &self.document.sections[section_idx].paragraphs[para_idx];
let default_char_shape_id: u32 = current_para.char_shape_id_at(char_offset).unwrap_or(0);
let default_para_shape_id: u16 = current_para.para_shape_id;
let inherited_line = creation_line::for_cursor(self, section_idx, para_idx, char_offset);
let (table, _) = self.build_inline_table(
content_width,
row_count,
col_count,
col_widths_hu,
row_heights_hu,
default_char_shape_id,
default_para_shape_id,
inherited_line,
InlineTableAnchor::Body,
)?;
self.document.sections[section_idx].raw_stream = None;
let para = &mut self.document.sections[section_idx].paragraphs[para_idx];
let ctrl_idx = para.controls.len();
para.controls.push(Control::Table(Box::new(table)));
para.ctrl_data_records.push(None);
let insert_utf16_pos = if char_offset < para.char_offsets.len() {
para.char_offsets[char_offset]
} else if !para.char_offsets.is_empty() {
let last_idx = para.char_offsets.len() - 1;
let last_char_len = para
.text
.chars()
.nth(last_idx)
.map(|c| c.len_utf16() as u32)
.unwrap_or(1);
para.char_offsets[last_idx] + last_char_len
} else {
0
};
for offset in para.char_offsets.iter_mut() {
if *offset >= insert_utf16_pos {
*offset += 8;
}
}
para.char_count += 8;
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,
previous_host_end,
&self.styles,
self.dpi,
hwp3_layout,
);
self.rebuild_section(section_idx);
self.event_log.push(DocumentEvent::TableRowInserted {
section: section_idx,
para: para_idx,
ctrl: ctrl_idx,
});
let logical_after = crate::document_core::helpers::text_to_logical_offset(
&self.document.sections[section_idx].paragraphs[para_idx],
char_offset,
) + 1;
Ok(crate::document_core::helpers::json_ok_with(&format!(
"\"paraIdx\":{},\"controlIdx\":{},\"logicalOffset\":{}",
para_idx, ctrl_idx, logical_after
)))
}
#[allow(clippy::too_many_arguments)]
pub fn create_table_in_cell_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
char_offset: usize,
row_count: u16,
col_count: u16,
col_widths_hu: Option<&[u32]>,
row_heights_hu: Option<&[u32]>,
treat_as_char: bool,
) -> Result<String, HwpError> {
use crate::model::paragraph::{CharShapeRef, LineSeg};
if row_count == 0 || col_count == 0 || col_count > 256 {
return Err(HwpError::RenderError(format!(
"행/열 수 범위 오류 (행={}, 열={})",
row_count, col_count
)));
}
let &(_, _, cell_para_idx) = path
.last()
.ok_or_else(|| HwpError::RenderError("경로가 비어있습니다".to_string()))?;
if !self.innermost_container_takes_table(section_idx, parent_para_idx, path) {
return Err(HwpError::RenderError(
"경로가 표 칸이나 머리말·꼬리말을 가리키지 않습니다".to_string(),
));
}
let (default_char_shape_id, default_para_shape_id, empty_para) = {
let paras = self.get_cell_paragraphs_mut_by_path(section_idx, parent_para_idx, path)?;
let para = paras.get(cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("칸 문단 {} 범위 초과", cell_para_idx))
})?;
let caret_len = para.text.chars().count() + para.controls.len();
if char_offset > caret_len {
return Err(HwpError::RenderError(format!(
"offset {} 이 칸 문단 길이 {} 를 넘는다",
char_offset, caret_len
)));
}
(
para.char_shape_id_at(char_offset).unwrap_or(0),
para.para_shape_id,
Paragraph::new_empty_like(para),
)
};
let (cell_width, pad_left, pad_right) = self
.resolve_innermost_cell_metrics(section_idx, parent_para_idx, path)
.ok_or_else(|| HwpError::RenderError("칸 폭을 알 수 없습니다".to_string()))?;
let inner_width = (cell_width - pad_left as i32 - pad_right as i32).max(0);
let content_width =
(inner_width - 2 * INLINE_TABLE_OUTER_MARGIN as i32).max(col_count as i32) as u32;
let inherited_line =
creation_line::for_empty(self, empty_para, default_char_shape_id, inner_width);
let (mut table, added_border_fill) = self.build_inline_table(
content_width,
row_count,
col_count,
col_widths_hu,
row_heights_hu,
default_char_shape_id,
default_para_shape_id,
inherited_line,
InlineTableAnchor::Cell,
)?;
if !treat_as_char {
let flags = table.common.attr & !1;
table.attr = flags;
table.common.attr = flags;
table.common.treat_as_char = false;
table.raw_ctrl_data[common_obj_offsets::FLAGS].copy_from_slice(&flags.to_le_bytes());
table.repeat_header = true;
table.raw_table_record_attr = 2 | (1 << 2);
}
let mut raw_header_extra = vec![0u8; 10];
raw_header_extra[0..2].copy_from_slice(&1u16.to_le_bytes());
raw_header_extra[4..6].copy_from_slice(&1u16.to_le_bytes());
let table_para = Paragraph {
text: String::new(),
char_count: 9,
control_mask: 0x0000_0800,
char_offsets: vec![],
char_shapes: vec![CharShapeRef {
start_pos: 0,
char_shape_id: default_char_shape_id,
}],
line_segs: vec![LineSeg {
text_start: 0,
line_height: 1000,
text_height: 1000,
baseline_distance: 850,
line_spacing: 600,
segment_width: if treat_as_char { inner_width } else { 0 },
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY,
..Default::default()
}],
para_shape_id: default_para_shape_id,
style_id: 0,
controls: vec![Control::Table(Box::new(table))],
ctrl_data_records: vec![None],
has_para_text: true,
raw_header_extra,
..Default::default()
};
self.document.sections[section_idx].raw_stream = None;
let paras = self.get_cell_paragraphs_mut_by_path(section_idx, parent_para_idx, path)?;
let tail = paras[cell_para_idx].split_at(char_offset);
let head = ¶s[cell_para_idx];
let table_para_idx = if head.text.is_empty() && head.controls.is_empty() {
paras[cell_para_idx] = table_para;
cell_para_idx
} else {
paras.insert(cell_para_idx + 1, table_para);
cell_para_idx + 1
};
paras.insert(table_para_idx + 1, tail);
let last = paras.len() - 1;
for (i, p) in paras.iter_mut().enumerate() {
p.char_count_msb = i == last;
}
for i in cell_para_idx..=table_para_idx + 1 {
self.reflow_cell_paragraph_by_path(section_idx, parent_para_idx, path, i);
}
self.recalculate_cell_paragraph_vpos_by_path(
section_idx,
parent_para_idx,
path,
cell_para_idx,
None,
);
self.mark_cell_control_dirty(section_idx, parent_para_idx, path[0].0);
if added_border_fill {
self.rebuild_section(section_idx);
} else {
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: path[0].0,
cell: path[0].1,
});
let mut cell_path: Vec<String> = path
.iter()
.enumerate()
.map(|(i, &(ctrl, cell, cpi))| {
let cpi = if i + 1 == path.len() {
table_para_idx
} else {
cpi
};
format!(
"{{\"controlIndex\":{},\"cellIndex\":{},\"cellParaIndex\":{}}}",
ctrl, cell, cpi
)
})
.collect();
cell_path.push("{\"controlIndex\":0,\"cellIndex\":0,\"cellParaIndex\":0}".to_string());
Ok(crate::document_core::helpers::json_ok_with(&format!(
"\"cellParaIdx\":{},\"controlIdx\":0,\"cellPath\":[{}]",
table_para_idx,
cell_path.join(",")
)))
}
fn innermost_container_takes_table(
&self,
section_idx: usize,
parent_para_idx: usize,
path: &[(usize, usize, usize)],
) -> bool {
let Some(mut para) = self
.document
.sections
.get(section_idx)
.and_then(|s| s.paragraphs.get(parent_para_idx))
else {
return false;
};
for (i, &(ctrl_idx, cell_idx, cell_para_idx)) in path.iter().enumerate() {
let paragraphs = match para.controls.get(ctrl_idx) {
Some(Control::Table(t)) => match t.cells.get(cell_idx) {
Some(cell) => &cell.paragraphs,
None => return false,
},
Some(control @ (Control::Header(_) | Control::Footer(_)))
if i == 0 && cell_idx == 0 =>
{
match control.header_footer_paragraphs() {
Some(paragraphs) => paragraphs,
None => return false,
}
}
_ => return false,
};
if i + 1 == path.len() {
return true;
}
let Some(next) = paragraphs.get(cell_para_idx) else {
return false;
};
para = next;
}
false
}
pub(crate) fn compute_cell_page_offset(
&self,
section_idx: usize,
parent_para_idx: usize,
cell_path: &[(usize, usize, usize)],
) -> (i32, i32) {
use crate::renderer::render_tree::{RenderNode, RenderNodeType};
if cell_path.is_empty() {
return (0, 0);
}
fn matches_cell_run(
node: &RenderNode,
parent_para: usize,
path: &[(usize, usize, usize)],
) -> bool {
if let RenderNodeType::TextRun(ref tr) = node.node_type {
return tr.cell_context.as_ref().is_some_and(|ctx| {
ctx.parent_para_index == parent_para
&& ctx.path.len() == path.len()
&& ctx
.path
.iter()
.zip(path.iter())
.all(|(a, b)| a.control_index == b.0 && a.cell_index == b.1)
});
}
for child in &node.children {
if matches!(child.node_type, RenderNodeType::Table(_)) {
continue;
}
if matches_cell_run(child, parent_para, path) {
return true;
}
}
false
}
fn find_cell(
node: &RenderNode,
parent_para: usize,
path: &[(usize, usize, usize)],
) -> Option<(f64, f64)> {
if let RenderNodeType::Table(_) = node.node_type {
if matches_cell_run(node, parent_para, path) {
let target_cell = path.last().unwrap().1;
for child in node.children.iter() {
if let RenderNodeType::TableCell(ref tc) = child.node_type {
if tc.model_cell_index == Some(target_cell as u32) {
return Some((child.bbox.x, child.bbox.y));
}
}
}
}
}
for child in &node.children {
if let Some(found) = find_cell(child, parent_para, path) {
return Some(found);
}
}
None
}
let total_pages = self.page_count();
for p in 0..total_pages {
if let Ok(tree) = self.build_page_tree(p) {
if let Some((px, py)) = find_cell(&tree.root, parent_para_idx, cell_path) {
let _ = section_idx;
return ((px * 75.0) as i32, (py * 75.0) as i32);
}
}
}
(0, 0)
}
pub fn get_table_cell_bboxes_at_page_native(
&self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
page: u32,
) -> Result<String, HwpError> {
let mut cells = Vec::new();
self.with_page_tree_cached(page, |tree| {
find_table_cells(
&tree.root,
section_idx,
parent_para_idx,
control_idx,
page as usize,
&mut cells,
);
Ok(())
})?;
Ok(format!("[{}]", cells.join(",")))
}
pub(crate) fn get_table_cell_bboxes_from_page(
&self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
page_hint: usize,
) -> Result<String, HwpError> {
let mut cells = Vec::new();
let total_pages = self.page_count() as usize;
let start = page_hint.min(total_pages.saturating_sub(1));
let mut found = false;
for page_num in start..total_pages {
let found_here = self.with_page_tree_cached(page_num as u32, |tree| {
Ok(find_table_cells(
&tree.root,
section_idx,
parent_para_idx,
control_idx,
page_num,
&mut cells,
))
})?;
if found_here {
found = true;
} else if found {
break;
}
}
if !found && start > 0 {
for page_num in (0..start).rev() {
let found_here = self.with_page_tree_cached(page_num as u32, |tree| {
Ok(find_table_cells(
&tree.root,
section_idx,
parent_para_idx,
control_idx,
page_num,
&mut cells,
))
})?;
if found_here {
found = true;
for fwd in (page_num + 1)..=start {
let found_fwd = self.with_page_tree_cached(fwd as u32, |tree| {
Ok(find_table_cells(
&tree.root,
section_idx,
parent_para_idx,
control_idx,
fwd,
&mut cells,
))
})?;
if !found_fwd {
break;
}
}
break;
}
}
}
Ok(format!("[{}]", cells.join(",")))
}
pub fn get_cell_picture_properties_by_path_native(
&self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
) -> Result<String, HwpError> {
let path = Self::parse_cell_path_json(cell_path_json)?;
let cell_para = self.resolve_paragraph_by_path(section_idx, parent_para_idx, &path)?;
let ctrl = cell_para.controls.get(inner_control_idx).ok_or_else(|| {
HwpError::RenderError(format!("셀 내 컨트롤 {} 범위 초과", inner_control_idx))
})?;
let pic = match ctrl {
Control::Picture(p) => p,
_ => {
return Err(HwpError::RenderError(
"지정된 셀 내 컨트롤이 그림이 아닙니다".to_string(),
))
}
};
Self::format_picture_properties_json(pic)
}
pub fn get_cell_shape_properties_by_path_native(
&self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
) -> Result<String, HwpError> {
let path = Self::parse_cell_path_json(cell_path_json)?;
let cell = self.resolve_cell_by_path(section_idx, parent_para_idx, &path)?;
let last_cell_para_idx = path.last().unwrap().2;
let cell_para = cell.paragraphs.get(last_cell_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("셀 내 문단 {} 범위 초과", last_cell_para_idx))
})?;
let ctrl = cell_para.controls.get(inner_control_idx).ok_or_else(|| {
HwpError::RenderError(format!("셀 내 컨트롤 {} 범위 초과", inner_control_idx))
})?;
let shape_ref = match ctrl {
Control::Shape(s) => s.as_ref(),
_ => {
return Err(HwpError::RenderError(
"지정된 셀 내 컨트롤이 Shape이 아닙니다".to_string(),
))
}
};
Self::format_shape_props_inner(shape_ref)
}
pub fn set_cell_picture_properties_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
props_json: &str,
) -> Result<String, HwpError> {
use crate::document_core::helpers::{json_bool, json_i32};
let path = Self::parse_cell_path_json(cell_path_json)?;
let restrict_change = json_bool(props_json, "restrictInPage");
let restrict_enabled_by_this_call = restrict_change.unwrap_or(false);
let clamp_horz =
restrict_enabled_by_this_call || json_i32(props_json, "horzOffset").is_some();
let clamp_vert =
restrict_enabled_by_this_call || json_i32(props_json, "vertOffset").is_some();
let caption_changed = {
let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
})?;
let current_para = Self::resolve_cell_paragraph_mut(section, parent_para_idx, &path)?;
let ctrl = current_para
.controls
.get_mut(inner_control_idx)
.ok_or_else(|| {
HwpError::RenderError(format!("셀 내 컨트롤 {} 범위 초과", inner_control_idx))
})?;
let pic = match ctrl {
Control::Picture(p) => p,
_ => {
return Err(HwpError::RenderError(
"지정된 셀 내 컨트롤이 그림이 아닙니다".to_string(),
))
}
};
let had_caption = pic.caption.is_some();
let caption_created = Self::apply_picture_props_inner(pic, props_json);
caption_created || (had_caption && pic.caption.is_none())
};
if caption_changed {
crate::parser::assign_auto_numbers(&mut self.document);
}
let section = &mut self.document.sections[section_idx];
Self::clamp_direct_owner_cell_picture_offsets(
section,
parent_para_idx,
&path,
inner_control_idx,
clamp_horz,
clamp_vert,
)?;
Self::sync_direct_owner_cell_for_picture(
section,
parent_para_idx,
&path,
inner_control_idx,
)?;
section.raw_stream = None;
self.recompose_section(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
let outer_table_ctrl = path.first().unwrap().0;
self.event_log.push(DocumentEvent::PictureResized {
section: section_idx,
para: parent_para_idx,
ctrl: outer_table_ctrl,
});
Ok("{\"ok\":true}".to_string())
}
pub fn delete_cell_picture_control_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
) -> Result<String, HwpError> {
self.delete_cell_control_by_path_native(
section_idx,
parent_para_idx,
cell_path_json,
inner_control_idx,
|c| matches!(c, Control::Picture(_)),
"그림이",
)
}
pub fn delete_cell_shape_control_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
) -> Result<String, HwpError> {
self.delete_cell_control_by_path_native(
section_idx,
parent_para_idx,
cell_path_json,
inner_control_idx,
|c| matches!(c, Control::Shape(_)),
"도형이",
)
}
pub fn delete_cell_table_control_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
) -> Result<String, HwpError> {
self.delete_cell_control_by_path_native(
section_idx,
parent_para_idx,
cell_path_json,
inner_control_idx,
|c| matches!(c, Control::Table(_)),
"표가",
)
}
fn delete_cell_control_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
accepts: fn(&Control) -> bool,
kind_label: &str,
) -> Result<String, HwpError> {
let path = Self::parse_cell_path_json(cell_path_json)?;
let deleted_table;
{
let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
})?;
let para = Self::resolve_cell_paragraph_mut(section, parent_para_idx, &path)?;
if inner_control_idx >= para.controls.len() {
return Err(HwpError::RenderError(format!(
"셀 내 컨트롤 {} 범위 초과",
inner_control_idx
)));
}
if !accepts(¶.controls[inner_control_idx]) {
return Err(HwpError::RenderError(format!(
"지정된 셀 내 컨트롤이 {} 아닙니다",
kind_label
)));
}
deleted_table = matches!(para.remove_control(inner_control_idx), Control::Table(_));
Self::reflow_paragraph_line_segs_after_control_delete(para, &self.styles, self.dpi);
}
let section = &mut self.document.sections[section_idx];
section.raw_stream = None;
self.recompose_section(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
if deleted_table {
self.event_log.push(DocumentEvent::CellTableDeleted {
section: section_idx,
para: parent_para_idx,
cell_path: path,
ctrl: inner_control_idx,
});
} else {
self.event_log.push(DocumentEvent::PictureDeleted {
section: section_idx,
para: parent_para_idx,
ctrl: path.first().unwrap().0,
});
}
Ok("{\"ok\":true}".to_string())
}
pub fn set_cell_shape_properties_by_path_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
cell_path_json: &str,
inner_control_idx: usize,
props_json: &str,
) -> Result<String, HwpError> {
let path = Self::parse_cell_path_json(cell_path_json)?;
let caption_changed = {
let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
})?;
let current_para = Self::resolve_cell_paragraph_mut(section, parent_para_idx, &path)?;
let ctrl = current_para
.controls
.get_mut(inner_control_idx)
.ok_or_else(|| {
HwpError::RenderError(format!("셀 내 컨트롤 {} 범위 초과", inner_control_idx))
})?;
let shape = match ctrl {
Control::Shape(s) => s.as_mut(),
_ => {
return Err(HwpError::RenderError(
"지정된 셀 내 컨트롤이 Shape이 아닙니다".to_string(),
))
}
};
Self::apply_shape_props_inner(shape, props_json)
};
if caption_changed {
crate::parser::assign_auto_numbers(&mut self.document);
}
self.finish_loaded_source_cache_after_object_edit(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
let outer_table_ctrl = path.first().unwrap().0;
self.event_log.push(DocumentEvent::PictureResized {
section: section_idx,
para: parent_para_idx,
ctrl: outer_table_ctrl,
});
Ok("{\"ok\":true}".to_string())
}
}
#[cfg(test)]
mod tests {
use crate::document_core::DocumentCore;
use crate::model::control::Control;
use crate::model::paragraph::CharShapeRef;
use crate::model::table::Table;
fn core_with_shaped_paragraph() -> DocumentCore {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().unwrap();
let para = &mut core.document.sections[0].paragraphs[0];
para.para_shape_id = 12;
para.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: 7,
}];
core
}
fn table_of(core: &DocumentCore) -> &Table {
core.document.sections[0]
.paragraphs
.iter()
.find_map(|p| {
p.controls.iter().find_map(|c| match c {
Control::Table(t) => Some(t.as_ref()),
_ => None,
})
})
.expect("표 컨트롤")
}
fn assert_cells_inherit_shape(table: &Table) {
assert!(!table.cells.is_empty(), "셀이 있어야 한다");
for cell in &table.cells {
let para = &cell.paragraphs[0];
assert_eq!(
para.para_shape_id, 12,
"셀 ({},{}) para_shape_id",
cell.row, cell.col
);
assert_eq!(
para.char_shapes.first().map(|cs| cs.char_shape_id),
Some(7),
"셀 ({},{}) char_shapes — 비면 charPrIDRef=0",
cell.row,
cell.col
);
}
}
#[test]
fn create_table_native_cells_inherit_char_shape() {
let mut core = core_with_shaped_paragraph();
core.create_table_native(0, 0, 0, 2, 3).unwrap();
assert_cells_inherit_shape(table_of(&core));
}
#[test]
fn create_table_ex_native_cells_inherit_char_shape() {
let mut core = core_with_shaped_paragraph();
core.create_table_ex_native(0, 0, 0, 2, 3, false, None, None)
.unwrap();
assert_cells_inherit_shape(table_of(&core));
}
fn core_with_mixed_shape_paragraph() -> DocumentCore {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().unwrap();
core.insert_text_native(0, 0, 0, "0123456789abcdefghij")
.unwrap();
let para = &mut core.document.sections[0].paragraphs[0];
para.para_shape_id = 12;
let boundary = para.char_offsets[10];
para.char_shapes = vec![
CharShapeRef {
start_pos: 0,
char_shape_id: 34,
},
CharShapeRef {
start_pos: boundary,
char_shape_id: 37,
},
];
core
}
fn assert_cells_inherit_cursor_shape(table: &Table) {
assert!(!table.cells.is_empty(), "셀이 있어야 한다");
for cell in &table.cells {
let para = &cell.paragraphs[0];
assert_eq!(
para.char_shapes.first().map(|cs| cs.char_shape_id),
Some(37),
"셀 ({},{}) — 커서 offset 의 글자모양(37)이 아니라 첫 엔트리(34)를 상속",
cell.row,
cell.col
);
}
}
#[test]
fn create_table_native_inherits_char_shape_at_cursor_offset() {
let mut core = core_with_mixed_shape_paragraph();
core.create_table_native(0, 0, 10, 2, 2).unwrap();
assert_cells_inherit_cursor_shape(table_of(&core));
}
#[test]
fn create_table_ex_native_inherits_char_shape_at_cursor_offset() {
let mut core = core_with_mixed_shape_paragraph();
core.create_table_ex_native(0, 0, 10, 2, 2, false, None, None)
.unwrap();
assert_cells_inherit_cursor_shape(table_of(&core));
}
#[test]
fn create_table_ex_native_tac_inherits_char_shape_at_cursor_offset() {
let mut core = core_with_mixed_shape_paragraph();
core.create_table_ex_native(0, 0, 10, 2, 2, true, None, None)
.unwrap();
assert_cells_inherit_cursor_shape(table_of(&core));
}
}