use crate::document_core::queries::field_query::{
caret_stops, cell_path_to_list, char_idx_at_stream_pos, cursor_paragraph, json_escape,
leading_anchor_pos, root_para_count, root_para_location, root_para_of, select_start_pos,
shape_lists, stream_len, word_end_from, word_starts, ListEntry, EXTENDED_CTRL_UNITS,
ROOT_LIST_ID,
};
use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::{AutoNumber, AutoNumberType, Control};
use crate::model::page::ColumnDef;
use crate::model::paragraph::{ColumnBreakType, Paragraph};
use crate::model::shape::{Caption, ShapeObject, TextBox};
use crate::model::style::{Alignment, HeadType, LineSpacingType, UnderlineType};
const LANGS: [&str; 7] = [
"Hangul", "Latin", "Hanja", "Japanese", "Other", "Symbol", "User",
];
fn bit(value: bool) -> u8 {
u8::from(value)
}
fn control_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
match ctrl {
Control::Table(t) => Some(&t.common),
Control::Shape(s) => Some(s.common()),
Control::Picture(p) => Some(&p.common),
_ => None,
}
}
fn control_common_mut(ctrl: &mut Control) -> Option<&mut crate::model::shape::CommonObjAttr> {
match ctrl {
Control::Table(t) => Some(&mut t.common),
Control::Shape(s) => Some(s.common_mut()),
Control::Picture(p) => Some(&mut p.common),
_ => None,
}
}
fn para_flag(shape: &crate::model::style::ParaShape, attr1_bit: u32, attr2_bit: u32) -> bool {
(shape.attr1 >> attr1_bit) & 1 != 0 || (shape.attr2 >> attr2_bit) & 1 != 0
}
fn align_code(alignment: Alignment) -> u8 {
match alignment {
Alignment::Justify => 0,
Alignment::Left => 1,
Alignment::Right => 2,
Alignment::Center => 3,
Alignment::Distribute => 4,
Alignment::Split => 5,
}
}
fn line_spacing_code(kind: LineSpacingType) -> u8 {
match kind {
LineSpacingType::Percent => 0,
LineSpacingType::Fixed => 1,
LineSpacingType::SpaceOnly => 2,
LineSpacingType::Minimum => 3,
}
}
fn heading_code(kind: HeadType) -> u8 {
match kind {
HeadType::None => 0,
HeadType::Outline => 1,
HeadType::Number => 2,
HeadType::Bullet => 3,
}
}
fn underline_code(kind: UnderlineType) -> u8 {
match kind {
UnderlineType::None => 0,
UnderlineType::Bottom => 1,
UnderlineType::Top => 2,
}
}
fn control_identity(ctrl: &Control) -> (&'static str, u32, &'static str) {
match ctrl {
Control::SectionDef(_) => ("secd", 2, "구역 정의"),
Control::ColumnDef(_) => ("cold", 2, "단 정의"),
Control::Table(_) => ("tbl", 11, "표"),
Control::Shape(shape) => (
"gso",
11,
match **shape {
crate::model::shape::ShapeObject::Group(_) => "그리기",
crate::model::shape::ShapeObject::Picture(_) => "그림",
_ => shape.shape_name(),
},
),
Control::Picture(_) => ("gso", 11, "그림"),
Control::Equation(_) => ("eqed", 11, "수식"),
Control::Form(_) => ("form", 11, "양식 개체"),
Control::Header(_) => ("head", 2, "머리말"),
Control::Footer(_) => ("foot", 2, "꼬리말"),
Control::Footnote(_) => ("fn", 2, "각주"),
Control::Endnote(_) => ("en", 2, "미주"),
Control::AutoNumber(_) => ("atno", 18, "번호 넣기"),
Control::NewNumber(_) => ("nwno", 2, "새 번호 지정"),
Control::PageNumberPos(_) => ("pgnp", 2, "쪽 번호 위치"),
Control::PageHide(_) => ("pghd", 2, "감추기"),
Control::Bookmark(_) => ("bokm", 2, "책갈피"),
Control::HiddenComment(_) => ("tcmt", 2, "숨은 설명"),
_ => ("", 0, ""),
}
}
fn collect_controls(
para: &Paragraph,
at: (u32, usize),
lists: &[ListEntry],
items: &mut Vec<String>,
) {
let (list_id, para_in_list) = at;
let control_positions = para.control_text_positions();
let rebuilt: Option<Vec<usize>> = {
let mut seen = control_positions.clone();
seen.sort_unstable();
let has_dup = seen.windows(2).any(|w| w[0] == w[1]);
let offsets_trustworthy = para.char_offsets.first().is_some_and(|o| *o > 0);
if has_dup && offsets_trustworthy {
let mut out = Vec::with_capacity(para.controls.len());
let mut p = 0usize;
let mut chars = para.char_offsets.iter().peekable();
for _ in 0..para.controls.len() {
while chars.peek().is_some_and(|off| (**off as usize) <= p) {
chars.next();
p += 1;
}
out.push(p);
p += EXTENDED_CTRL_UNITS;
}
Some(out)
} else {
None
}
};
for (ci, ctrl) in para.controls.iter().enumerate() {
let (id, ch, desc) = control_identity(ctrl);
let pos = if let Some(rebuilt) = &rebuilt {
rebuilt.get(ci).copied().unwrap_or(0)
} else {
control_positions
.get(ci)
.map(|char_idx| {
let placeholders_before = control_positions[..ci]
.iter()
.filter(|p| *p < char_idx)
.count();
let plain_before = char_idx.saturating_sub(placeholders_before);
plain_before + ci * EXTENDED_CTRL_UNITS
})
.unwrap_or(0)
};
items.push(format!(
"{{\"ctrlId\":{},\"ctrlCh\":{},\"userDesc\":{},\"list\":{},\"para\":{},\"pos\":{},\"controlIndex\":{},\"props\":{}}}",
json_escape(id),
ch,
json_escape(desc),
list_id,
para_in_list,
pos,
ci,
control_props_json(ctrl),
));
let child_of = |cell_index: usize| {
lists
.iter()
.find(|l| {
l.host_list_id == list_id
&& l.host_para_index == para_in_list
&& l.control_index == ci
&& l.cell_index == cell_index
})
.map(|l| l.list_id)
};
match ctrl {
Control::Table(table) => {
for (cell_index, cell) in table.cells.iter().enumerate() {
let Some(child) = child_of(cell_index) else {
continue;
};
for (pi, cell_para) in cell.paragraphs.iter().enumerate() {
collect_controls(cell_para, (child, pi), lists, items);
}
}
}
Control::Shape(shape) => {
for (node, paragraphs) in shape_lists(shape) {
let Some(child) = child_of(node) else {
continue;
};
for (pi, box_para) in paragraphs.iter().enumerate() {
collect_controls(box_para, (child, pi), lists, items);
}
}
}
_ => {}
}
}
}
fn escape_outside_cp949(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut buf = [0u8; 4];
for ch in text.chars() {
let one = ch.encode_utf8(&mut buf);
let (_, _, had_errors) = encoding_rs::EUC_KR.encode(one);
if had_errors {
out.push_str(&format!("&#{};", ch as u32));
} else {
out.push(ch);
}
}
out
}
fn scan_push(items: &mut Vec<(u8, String, u8)>, state: u8, text: String) {
items.push((state, text, 0));
}
fn scan_paragraph(
para: &Paragraph,
at: (u32, usize),
lists: &[ListEntry],
items: &mut Vec<(u8, String, u8)>,
) {
let (list_id, para_in_list) = at;
let mut state: u8 = if para_in_list == 0 { 2 } else { 3 };
for ctrl in para.controls.iter() {
if matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)) {
items.push((state, String::new(), 1));
state = 2;
}
}
let control_positions = para.control_text_positions();
let mut inserts: Vec<(usize, String)> = Vec::new();
for fr in para.field_ranges.iter() {
if fr.start_char_idx != fr.end_char_idx {
continue;
}
if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
if let Some(guide) = field.guide_text() {
if !guide.is_empty() {
inserts.push((fr.start_char_idx, guide.to_string()));
}
}
}
}
inserts.sort_by_key(|(at, _)| *at);
let raw: Vec<char> = para.text.chars().collect();
let mut chars: Vec<char> = Vec::with_capacity(raw.len());
let mut shift_at: Vec<(usize, usize)> = Vec::new(); let mut shift = 0usize;
let mut next_insert = 0usize;
for (i, ch) in raw.iter().enumerate() {
while next_insert < inserts.len() && inserts[next_insert].0 == i {
let text = &inserts[next_insert].1;
chars.extend(text.chars());
shift += text.chars().count();
next_insert += 1;
}
shift_at.push((i, shift));
chars.push(*ch);
}
while next_insert < inserts.len() {
chars.extend(inserts[next_insert].1.chars());
shift += inserts[next_insert].1.chars().count();
next_insert += 1;
}
let shift_for = |orig: usize| -> usize {
match shift_at.binary_search_by_key(&orig, |(i, _)| *i) {
Ok(k) => shift_at[k].1,
Err(_) => shift,
}
};
let mut cut = 0usize;
for (ci, ctrl) in para.controls.iter().enumerate() {
let nested: Vec<(usize, &[Paragraph])> = match ctrl {
Control::Table(table) => (0..table.cells.len())
.filter_map(|cell| {
table
.cells
.get(cell)
.map(|c| (cell, c.paragraphs.as_slice()))
})
.collect(),
Control::Shape(shape) => shape_lists(shape),
_ => Vec::new(),
};
if matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)) {
continue;
}
let original = control_positions
.get(ci)
.copied()
.unwrap_or(raw.len())
.min(raw.len());
let here = (original + shift_for(original)).min(chars.len());
let run: String = chars[cut.min(here)..here].iter().collect();
items.push((state, run, if nested.is_empty() { 2 } else { 0 }));
state = 2;
let owns_marker = matches!(
ctrl,
Control::Table(_) | Control::Shape(_) | Control::Picture(_) | Control::Equation(_)
) && raw.get(original) == Some(&'\u{FFFC}')
&& para.char_offsets.get(original).is_some_and(|start| {
para.char_offsets
.get(original + 1)
.copied()
.or_else(|| para.char_count.checked_sub(1))
.and_then(|end| end.checked_sub(*start))
.is_some_and(|span| span >= 8 && span.is_multiple_of(8))
});
cut = cut.max(here + usize::from(owns_marker));
if nested.is_empty() {
continue;
}
let mut entered = false;
for (node, paragraphs) in nested {
let child = lists
.iter()
.find(|l| {
l.host_list_id == list_id
&& l.host_para_index == para_in_list
&& l.control_index == ci
&& l.cell_index == node
})
.map(|l| l.list_id);
let Some(child_list) = child else { continue };
for (pi, child_para) in paragraphs.iter().enumerate() {
let before = items.len();
scan_paragraph(child_para, (child_list, pi), lists, items);
if !entered {
if let Some(first) = items.get_mut(before) {
first.0 = if list_id == ROOT_LIST_ID { 4 } else { 5 };
}
entered = true;
}
}
}
if entered {
state = 5;
}
}
let tail: String = chars[cut.min(chars.len())..].iter().collect();
scan_push(items, state, format!("{}\r\n", tail));
}
fn control_props_json(ctrl: &Control) -> String {
let common = match ctrl {
Control::Table(t) => Some(&t.common),
Control::Shape(s) => Some(s.common()),
Control::Picture(p) => Some(&p.common),
_ => None,
};
let Some(c) = common else {
return "{}".to_string();
};
format!(
"{{\"Lock\":{},\"TreatAsChar\":{},\"AllowOverlap\":{},\"TextWrap\":{},\
\"Width\":{},\"Height\":{},\"HorzOffset\":{},\"VertOffset\":{}}}",
u8::from(c.locked),
u8::from(c.treat_as_char),
u8::from(c.allow_overlap),
(c.attr >> 21) & 0x03,
c.width,
c.height,
c.horizontal_offset,
c.vertical_offset,
)
}
impl DocumentCore {
pub fn char_shape_set_json(&self, list_id: u32, para_in_list: usize, pos: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "{}".to_string();
};
let char_idx = char_idx_at_stream_pos(para, pos);
let shape_id = para.char_shape_id_at(char_idx).unwrap_or(0);
let Some(raw) = self.document.doc_info.char_shapes.get(shape_id as usize) else {
return "{}".to_string();
};
let style = self.styles.char_styles.get(shape_id as usize);
let mut items: Vec<String> = Vec::new();
for (i, lang) in LANGS.iter().enumerate() {
if let Some(cs) = style {
let raw_name = cs.font_family_for_lang(i);
let name = crate::renderer::style_resolver::primary_font_name(&raw_name);
items.push(format!("\"FaceName{}\":{}", lang, json_escape(name)));
}
items.push(format!("\"Size{}\":{}", lang, raw.relative_sizes[i]));
items.push(format!("\"Ratio{}\":{}", lang, raw.ratios[i]));
items.push(format!("\"Spacing{}\":{}", lang, raw.spacings[i]));
items.push(format!("\"Offset{}\":{}", lang, raw.char_offsets[i]));
}
items.push(format!("\"Height\":{}", raw.base_size));
items.push(format!("\"Bold\":{}", bit(raw.bold)));
items.push(format!("\"Italic\":{}", bit(raw.italic)));
items.push(format!("\"Emboss\":{}", bit(raw.emboss)));
items.push(format!("\"Engrave\":{}", bit(raw.engrave)));
items.push(format!("\"SuperScript\":{}", bit(raw.superscript)));
items.push(format!("\"SubScript\":{}", bit(raw.subscript)));
items.push(format!(
"\"UnderlineType\":{}",
underline_code(raw.underline_type)
));
items.push(format!("\"UnderlineShape\":{}", raw.underline_shape));
items.push(format!("\"OutlineType\":{}", raw.outline_type));
items.push(format!("\"ShadowType\":{}", raw.shadow_type));
items.push(format!("\"ShadowOffsetX\":{}", raw.shadow_offset_x));
items.push(format!("\"ShadowOffsetY\":{}", raw.shadow_offset_y));
items.push(format!("\"StrikeOutType\":{}", bit(raw.strikethrough)));
items.push(format!("\"DiacSymMark\":{}", raw.emphasis_dot));
items.push(format!("\"UseFontSpace\":{}", bit(raw.use_font_space)));
items.push(format!("\"UseKerning\":{}", bit(raw.kerning)));
items.push(format!("\"TextColor\":{}", raw.text_color));
items.push(format!("\"ShadeColor\":{}", raw.shade_color));
items.push(format!("\"UnderlineColor\":{}", raw.underline_color));
items.push(format!("\"ShadowColor\":{}", raw.shadow_color));
format!("{{{}}}", items.join(","))
}
pub fn para_shape_set_json(&self, list_id: u32, para_in_list: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "{}".to_string();
};
let Some(shape) = self
.document
.doc_info
.para_shapes
.get(para.para_shape_id as usize)
else {
return "{}".to_string();
};
let items = [
format!("\"LeftMargin\":{}", shape.margin_left),
format!("\"RightMargin\":{}", shape.margin_right),
format!("\"Indentation\":{}", shape.indent),
format!("\"PrevSpacing\":{}", shape.spacing_before),
format!("\"NextSpacing\":{}", shape.spacing_after),
format!("\"LineSpacing\":{}", shape.line_spacing),
format!(
"\"LineSpacingType\":{}",
line_spacing_code(shape.line_spacing_type)
),
format!("\"AlignType\":{}", align_code(shape.alignment)),
format!("\"HeadingType\":{}", heading_code(shape.head_type)),
format!("\"Level\":{}", shape.para_level),
format!("\"WidowOrphan\":{}", bit(para_flag(shape, 16, 5))),
format!("\"KeepWithNext\":{}", bit(para_flag(shape, 17, 6))),
format!("\"KeepLinesTogether\":{}", bit(para_flag(shape, 18, 7))),
format!("\"PagebreakBefore\":{}", bit(para_flag(shape, 19, 8))),
];
format!("{{{}}}", items.join(","))
}
pub fn apply_char_format_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
start_pos: usize,
end_pos: usize,
props_json: &str,
) -> Result<String, HwpError> {
let (start_char, end_char) = {
let para = self
.cursor_paragraph_ref(list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let last = para.text.chars().count();
(
char_idx_at_stream_pos(para, start_pos).min(last),
char_idx_at_stream_pos(para, end_pos).min(last),
)
};
if start_char >= end_char {
return Ok(r#"{"ok":false,"reason":"빈 범위"}"#.to_string());
}
if list_id == ROOT_LIST_ID {
let (sec, para) = root_para_location(self, para_in_list).ok_or_else(|| {
HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list))
})?;
return self.apply_char_format_native(sec, para, start_char, end_char, props_json);
}
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let path = cell_path_to_list(&lists, list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField("셀 경로를 세울 수 없음".into()))?;
let section_index = entry.section_index;
let host_para = root_para_of(&lists, entry);
self.apply_char_format_in_cell_by_path(
section_index,
host_para,
&path,
start_char,
end_char,
props_json,
)
}
pub fn insert_text_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
pos: usize,
text: &str,
) -> Result<String, HwpError> {
let char_idx = {
let para = self
.cursor_paragraph_ref(list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
char_idx_at_stream_pos(para, pos).min(para.text.chars().count())
};
if list_id == ROOT_LIST_ID {
let (sec, para) = root_para_location(self, para_in_list).ok_or_else(|| {
HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list))
})?;
return self.insert_text_native(sec, para, char_idx, text);
}
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let path = cell_path_to_list(&lists, list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField("셀 경로를 세울 수 없음".into()))?;
let section_index = entry.section_index;
let host_para = root_para_of(&lists, entry);
self.insert_text_in_cell_by_path(section_index, host_para, &path, char_idx, text)
}
pub fn controls_json(&self) -> String {
let (_, lists) = self.collect_fields_and_lists();
let mut items: Vec<String> = Vec::new();
let mut para_in_body = 0usize;
for section in self.document.sections.iter() {
for para in section.paragraphs.iter() {
collect_controls(para, (ROOT_LIST_ID, para_in_body), &lists, &mut items);
para_in_body += 1;
}
}
format!("[{}]", items.join(","))
}
pub fn scan_items_json(&self) -> String {
let (_, lists) = self.collect_fields_and_lists();
let mut items: Vec<(u8, String, u8)> = Vec::new();
let mut para_in_body = 0usize;
for section in self.document.sections.iter() {
for para in section.paragraphs.iter() {
scan_paragraph(para, (ROOT_LIST_ID, para_in_body), &lists, &mut items);
para_in_body += 1;
}
}
let body: Vec<String> = items
.iter()
.map(|(state, text, kind)| {
format!(
"{{\"state\":{},\"kind\":{},\"text\":{}}}",
state,
kind,
json_escape(text)
)
})
.collect();
format!("[{}]", body.join(","))
}
fn text_file_content(&self) -> String {
let (_, lists) = self.collect_fields_and_lists();
let mut items: Vec<(u8, String, u8)> = Vec::new();
let mut para_in_body = 0usize;
for section in self.document.sections.iter() {
for para in section.paragraphs.iter() {
scan_paragraph(para, (ROOT_LIST_ID, para_in_body), &lists, &mut items);
para_in_body += 1;
}
}
let mut out = String::new();
for (_, text, kind) in items.iter() {
if *kind == 1 {
continue; }
out.push_str(text);
if *kind != 2 && !text.ends_with("\r\n") {
out.push_str("\r\n");
}
}
if out.ends_with("\r\n") {
out.truncate(out.len() - 2);
}
out
}
pub fn text_file_json(&self) -> String {
json_escape(&escape_outside_cp949(&self.text_file_content()))
}
pub fn text_file_unicode_json(&self) -> String {
json_escape(&self.text_file_content())
}
pub fn delete_control_at(
&mut self,
list_id: u32,
para_in_list: usize,
control_index: usize,
) -> Result<String, HwpError> {
if list_id != ROOT_LIST_ID {
return Ok(
r#"{"ok":false,"reason":"본문 밖 컨트롤은 아직 다루지 않는다"}"#.to_string(),
);
}
let (sec, para) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
self.delete_control_native(sec, para, control_index)
}
pub fn set_control_lock(
&mut self,
para_in_list: Option<usize>,
control_index: Option<usize>,
locked: bool,
) -> Result<String, HwpError> {
let target = match para_in_list {
Some(p) => Some(
root_para_location(self, p)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", p)))?,
),
None => None,
};
let mut touched = 0usize;
let mut touched_sections: Vec<usize> = Vec::new();
for (si, section) in self.document.sections.iter_mut().enumerate() {
for (pi, para) in section.paragraphs.iter_mut().enumerate() {
if let Some((ts, tp)) = target {
if si != ts || pi != tp {
continue;
}
}
for (ci, ctrl) in para.controls.iter_mut().enumerate() {
if let Some(want) = control_index {
if ci != want {
continue;
}
}
let common = match ctrl {
Control::Table(t) => Some(&mut t.common),
Control::Shape(s) => Some(s.common_mut()),
Control::Picture(p) => Some(&mut p.common),
_ => None,
};
let Some(c) = common else { continue };
touched_sections.push(si);
c.locked = locked;
if locked {
c.attr |= 1 << 30;
} else {
c.attr &= !(1u32 << 30);
}
touched += 1;
}
}
}
for si in touched_sections {
if let Some(section) = self.document.sections.get_mut(si) {
section.raw_stream = None;
}
}
Ok(format!("{{\"ok\":true,\"touched\":{}}}", touched))
}
pub fn cur_field_state(&self, list_id: u32, para_in_list: usize, pos: usize) -> u32 {
const IN_FIELD: u32 = 0x10;
const KIND_CELL: u32 = 1;
const KIND_CLICK_HERE: u32 = 2;
let (fields, lists) = self.collect_fields_and_lists();
let in_cell = lists.iter().any(|l| l.list_id == list_id && l.is_cell);
let mut state = if in_cell { KIND_CELL } else { 0 };
for f in &fields {
if f.list_id != list_id {
continue;
}
if f.start_pos == 0 && f.end_pos == 0 {
state = IN_FIELD | KIND_CELL;
continue;
}
if f.para_in_list == para_in_list && pos >= f.start_pos && pos <= f.end_pos {
return IN_FIELD | KIND_CLICK_HERE;
}
}
state
}
pub fn cell_shape_set_json(&self, list_id: u32) -> String {
let (_, lists) = self.collect_fields_and_lists();
let Some(entry) = lists.iter().find(|l| l.list_id == list_id) else {
return "{}".to_string();
};
if !entry.is_cell {
return "{}".to_string();
}
let Some(section) = self.document.sections.get(entry.section_index) else {
return "{}".to_string();
};
let Some(para) = section.paragraphs.get(entry.host_para_index) else {
return "{}".to_string();
};
let Some(Control::Table(table)) = para.controls.get(entry.control_index) else {
return "{}".to_string();
};
let Some(cell) = table.cells.get(entry.cell_index) else {
return "{}".to_string();
};
format!(
"{{\"Width\":{},\"Height\":{},\"VertAlign\":{}}}",
cell.width, cell.height, cell.vertical_align as u8,
)
}
pub fn objects_json(&self) -> String {
let (_, lists) = self.collect_fields_and_lists();
let mut items: Vec<String> = Vec::new();
let mut para_base = 0usize;
for (sec_idx, section) in self.document.sections.iter().enumerate() {
for (para_off, para) in section.paragraphs.iter().enumerate() {
let para_idx = para_base + para_off;
for (ci, ctrl) in para.controls.iter().enumerate() {
let kind = match ctrl {
Control::Shape(_) => "shape",
Control::Picture(_) => "picture",
Control::Equation(_) => "equation",
Control::Table(_) => "table",
_ => continue,
};
let list_id = lists
.iter()
.find(|l| {
!l.is_cell
&& l.host_list_id == ROOT_LIST_ID
&& l.section_index == sec_idx
&& l.host_para_index == para_off
&& l.control_index == ci
})
.map(|l| l.list_id.to_string())
.unwrap_or_else(|| "null".to_string());
let anchored = match ctrl {
Control::Table(t) => !t.common.treat_as_char,
Control::Shape(s) => !s.common().treat_as_char,
_ => true,
};
items.push(format!(
"{{\"para\":{},\"controlIndex\":{},\"kind\":\"{}\",\"listId\":{},\"anchored\":{}}}",
para_idx, ci, kind, list_id, anchored
));
}
}
para_base += section.paragraphs.len();
}
format!("[{}]", items.join(","))
}
pub fn split_para_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
pos: usize,
) -> Result<String, HwpError> {
let char_idx = {
let para = self
.cursor_paragraph_ref(list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
char_idx_at_stream_pos(para, pos).min(para.text.chars().count())
};
if list_id == ROOT_LIST_ID {
let (sec, para) = root_para_location(self, para_in_list).ok_or_else(|| {
HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list))
})?;
return self.split_paragraph_native(sec, para, char_idx, None);
}
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let path = cell_path_to_list(&lists, list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField("셀 경로를 세울 수 없음".into()))?;
let section_index = entry.section_index;
let host_para = root_para_of(&lists, entry);
self.split_paragraph_in_cell_by_path(section_index, host_para, &path, char_idx, None)
}
pub fn resize_control_at(
&mut self,
para_in_list: usize,
control_index: usize,
d_width: i32,
d_height: i32,
) -> Result<String, HwpError> {
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let ctrl = para
.controls
.get_mut(control_index)
.ok_or_else(|| HwpError::InvalidField(format!("컨트롤 {} 없음", control_index)))?;
let common = match ctrl {
Control::Table(t) => Some(&mut t.common),
Control::Shape(s) => Some(s.common_mut()),
Control::Picture(p) => Some(&mut p.common),
_ => None,
};
let Some(c) = common else {
return Ok(r#"{"ok":false,"reason":"크기를 가진 개체가 아니다"}"#.to_string());
};
c.width = (c.width as i64 + d_width as i64).max(0) as u32;
c.height = (c.height as i64 + d_height as i64).max(0) as u32;
let (w, h) = (c.width, c.height);
let sa = match para
.controls
.get_mut(control_index)
.expect("바로 위에서 확인했다")
{
Control::Shape(s) => Some(s.shape_attr_mut()),
Control::Picture(p) => Some(&mut p.shape_attr),
_ => None,
};
if let Some(sa) = sa {
sa.current_width = w;
sa.current_height = h;
if sa.original_width > 0 {
let sx = f64::from(w) / f64::from(sa.original_width);
sa.render_sx = if sa.render_sx < 0.0 { -sx } else { sx };
}
if sa.original_height > 0 {
let sy = f64::from(h) / f64::from(sa.original_height);
sa.render_sy = if sa.render_sy < 0.0 { -sy } else { sy };
}
sa.rotation_center.x = (w / 2) as i32;
sa.rotation_center.y = (h / 2) as i32;
sa.raw_rendering = Vec::new();
}
section.raw_stream = None;
Ok(r#"{"ok":true}"#.to_string())
}
pub fn move_control_at(
&mut self,
para_in_list: usize,
control_index: usize,
dx: i32,
dy: i32,
) -> Result<String, HwpError> {
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let ctrl = para
.controls
.get_mut(control_index)
.ok_or_else(|| HwpError::InvalidField(format!("컨트롤 {} 없음", control_index)))?;
let common = match ctrl {
Control::Table(t) => Some(&mut t.common),
Control::Shape(s) => Some(s.common_mut()),
Control::Picture(p) => Some(&mut p.common),
_ => None,
};
let Some(c) = common else {
return Ok(r#"{"ok":false,"reason":"자리를 가진 개체가 아니다"}"#.to_string());
};
if c.treat_as_char {
return Ok(r#"{"ok":true,"moved":false}"#.to_string());
}
c.horizontal_offset = (c.horizontal_offset as i64 + dx as i64).max(0) as u32;
c.vertical_offset = (c.vertical_offset as i64 + dy as i64).max(0) as u32;
section.raw_stream = None;
Ok(r#"{"ok":true,"moved":true}"#.to_string())
}
pub fn set_control_z_order_at(
&mut self,
para_in_list: usize,
control_index: usize,
mode: &str,
) -> Result<String, HwpError> {
use crate::model::shape::TextWrap;
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
if let Some(wrap) = match mode {
"behindText" => Some(TextWrap::BehindText),
"inFrontOfText" => Some(TextWrap::InFrontOfText),
_ => None,
} {
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let ctrl = para
.controls
.get_mut(control_index)
.ok_or_else(|| HwpError::InvalidField(format!("컨트롤 {} 없음", control_index)))?;
let Some(c) = control_common_mut(ctrl) else {
return Ok(r#"{"ok":false,"reason":"배치를 가진 개체가 아니다"}"#.to_string());
};
c.text_wrap = wrap;
crate::serializer::control::sync_text_wrap_bits(c);
section.raw_stream = None;
return Ok(r#"{"ok":true}"#.to_string());
}
let mut slots: Vec<(usize, usize, i32)> = Vec::new();
for (pi, para) in section.paragraphs.iter().enumerate() {
for (ci, ctrl) in para.controls.iter().enumerate() {
if let Some(c) = control_common(ctrl) {
slots.push((pi, ci, c.z_order));
}
}
}
let Some(&(_, _, target_z)) = slots
.iter()
.find(|&&(pi, ci, _)| pi == para_idx && ci == control_index)
else {
return Ok(r#"{"ok":false,"reason":"순서를 가진 개체가 아니다"}"#.to_string());
};
let top = slots.iter().map(|&(_, _, z)| z).max().unwrap_or(target_z);
let bottom = slots.iter().map(|&(_, _, z)| z).min().unwrap_or(target_z);
let renumber = |z: i32| -> i32 {
match mode {
"front" => {
if z == target_z {
top
} else if z > target_z {
z - 1
} else {
z
}
}
"back" => {
if z == target_z {
bottom
} else if z < target_z {
z + 1
} else {
z
}
}
"forward" => {
if z == target_z && target_z < top {
z + 1
} else if z == target_z + 1 && target_z < top {
z - 1
} else {
z
}
}
"backward" => {
if z == target_z && target_z > bottom {
z - 1
} else if z == target_z - 1 && target_z > bottom {
z + 1
} else {
z
}
}
_ => z,
}
};
if !matches!(mode, "front" | "back" | "forward" | "backward") {
return Ok(format!(
r#"{{"ok":false,"reason":"모르는 갈래: {}"}}"#,
mode
));
}
let mut moved = false;
for (pi, ci, z) in slots {
let new_z = renumber(z);
if new_z == z {
continue;
}
moved = true;
if let Some(c) = section
.paragraphs
.get_mut(pi)
.and_then(|p| p.controls.get_mut(ci))
.and_then(control_common_mut)
{
c.z_order = new_z;
}
}
if moved {
section.raw_stream = None;
}
Ok(format!(r#"{{"ok":true,"moved":{}}}"#, moved))
}
pub fn set_control_flip_at(
&mut self,
para_in_list: usize,
control_index: usize,
vertical: bool,
org_state: bool,
) -> Result<String, HwpError> {
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let Some(Control::Shape(shape)) = para.controls.get_mut(control_index) else {
return Ok(r#"{"ok":false,"reason":"뒤집을 수 있는 개체가 아니다"}"#.to_string());
};
let sa = shape.shape_attr_mut();
let axis_bit: u32 = if vertical { 0x02 } else { 0x01 };
if org_state && sa.flip & axis_bit == 0 {
return Ok(r#"{"ok":true,"moved":false}"#.to_string());
}
sa.flip ^= axis_bit;
let on = sa.flip & axis_bit != 0;
let (cur, org) = if vertical {
(sa.current_height, sa.original_height)
} else {
(sa.current_width, sa.original_width)
};
let scale = if org > 0 {
f64::from(cur) / f64::from(org)
} else {
1.0
};
let shift = if on {
f64::from(cur + (cur & 1) - 2 * (org & 1))
} else {
0.0
};
let sign = if on { -1.0 } else { 1.0 };
if vertical {
sa.vert_flip = on;
sa.render_sy = sign * scale;
sa.render_ty = shift;
} else {
sa.horz_flip = on;
sa.render_sx = sign * scale;
sa.render_tx = shift;
}
sa.raw_rendering = Vec::new();
section.raw_stream = None;
Ok(r#"{"ok":true,"moved":true}"#.to_string())
}
pub fn page_caret_starts(&self) -> Result<String, HwpError> {
use crate::renderer::pagination::PageItem;
let mut out: Vec<String> = Vec::new();
for (sec_idx, pr) in self.pagination.iter().enumerate() {
for page in pr.pages.iter() {
let mut found: Option<(usize, usize)> = None;
'items: for col in &page.column_contents {
for item in &col.items {
match item {
PageItem::PartialTable {
is_continuation: true,
..
} => continue,
PageItem::PartialParagraph {
para_index,
start_line,
..
} => {
let ts = self
.document
.sections
.get(sec_idx)
.and_then(|s| s.paragraphs.get(*para_index))
.and_then(|p| p.line_segs.get(*start_line))
.map(|seg| seg.text_start as usize)
.unwrap_or(0);
found = Some((*para_index, ts));
break 'items;
}
PageItem::FullParagraph { para_index }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => {
found = Some((*para_index, 0));
break 'items;
}
_ => continue,
}
}
}
let Some((para_index, pos)) = found else {
let cell = page
.column_contents
.iter()
.flat_map(|col| col.items.iter())
.find_map(|item| match item {
PageItem::PartialTable {
para_index,
control_index,
start_row,
..
} => self.first_cell_list_of_row(
sec_idx,
*para_index,
*control_index,
*start_row,
),
_ => None,
});
match cell {
Some(list_id) => {
out.push(format!("{{\"list\":{},\"para\":0,\"pos\":0}}", list_id))
}
None => out.push("null".to_string()),
}
continue;
};
let before: usize = self
.document
.sections
.iter()
.take(sec_idx)
.map(|s| s.paragraphs.len())
.sum();
let para_in_list = before + para_index;
let start = self
.document
.sections
.get(sec_idx)
.and_then(|s| s.paragraphs.get(para_index))
.map(leading_anchor_pos)
.unwrap_or(0);
out.push(format!(
"{{\"list\":0,\"para\":{},\"pos\":{}}}",
para_in_list,
pos.max(start)
));
}
}
Ok(format!("[{}]", out.join(",")))
}
pub fn char_index_at(
&self,
list_id: u32,
para_in_list: usize,
pos: usize,
) -> Result<String, HwpError> {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return Ok("{\"charIndex\":0}".to_string());
};
Ok(format!(
"{{\"charIndex\":{}}}",
char_idx_at_stream_pos(para, pos)
))
}
pub fn page_text(&self, page_index: usize) -> Result<String, HwpError> {
let starts: Vec<(usize, usize)> = {
let raw = self.page_caret_starts()?;
let mut out = Vec::new();
for chunk in raw.split("{\"list\":").skip(1) {
let para = chunk
.split("\"para\":")
.nth(1)
.and_then(|s| s.split([',', '}']).next())
.and_then(|s| s.trim().parse::<usize>().ok())
.unwrap_or(0);
let pos = chunk
.split("\"pos\":")
.nth(1)
.and_then(|s| s.split([',', '}']).next())
.and_then(|s| s.trim().parse::<usize>().ok())
.unwrap_or(0);
out.push((para, pos));
}
out
};
let Some(&(from_para, from_pos)) = starts.get(page_index) else {
return Ok(json_escape(""));
};
let last_para = root_para_count(self).saturating_sub(1);
let (to_para, to_pos) = starts
.get(page_index + 1)
.copied()
.unwrap_or((last_para + 1, 0));
let mut lines: Vec<String> = Vec::new();
for p in from_para..=to_para.min(last_para) {
let Some(para) = self.cursor_paragraph_ref(ROOT_LIST_ID, p) else {
continue;
};
let chars: Vec<char> = para.text.chars().collect();
let begin = if p == from_para {
char_idx_at_stream_pos(para, from_pos)
} else {
0
};
let end = if p == to_para {
char_idx_at_stream_pos(para, to_pos)
} else {
chars.len()
};
lines.push(
chars[begin.min(chars.len())..end.min(chars.len())]
.iter()
.collect(),
);
}
if page_index + 1 >= starts.len() {
lines.push(String::new());
}
Ok(json_escape(&lines.join("\r\n")))
}
pub fn object_cycle_json(&self) -> Result<String, HwpError> {
use crate::renderer::pagination::PageItem;
let mut page_of: std::collections::HashMap<(usize, usize), usize> =
std::collections::HashMap::new();
let mut page_no = 0usize;
for (sec_idx, pr) in self.pagination.iter().enumerate() {
for page in pr.pages.iter() {
for col in &page.column_contents {
for item in &col.items {
let para = match item {
PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => Some(*para_index),
_ => None,
};
if let Some(p) = para {
page_of.entry((sec_idx, p)).or_insert(page_no);
}
}
}
page_no += 1;
}
}
let mut out: Vec<String> = Vec::new();
let mut para_in_list = 0usize;
for (sec_idx, section) in self.document.sections.iter().enumerate() {
for (para_idx, para) in section.paragraphs.iter().enumerate() {
for (ci, ctrl) in para.controls.iter().enumerate() {
let common = match ctrl {
Control::Table(t) => Some(&t.common),
Control::Shape(s) => Some(s.common()),
Control::Picture(p) => Some(&p.common),
_ => None,
};
let Some(c) = common else { continue };
let page = page_of.get(&(sec_idx, para_idx)).copied().unwrap_or(0);
out.push(format!(
"{{\"para\":{},\"controlIndex\":{},\"page\":{},\"z\":{}}}",
para_in_list, ci, page, c.z_order
));
}
para_in_list += 1;
}
}
Ok(format!("[{}]", out.join(",")))
}
fn first_cell_list_of_row(
&self,
section_index: usize,
host_para: usize,
control_index: usize,
row: usize,
) -> Option<u32> {
let (_, lists) = self.collect_fields_and_lists();
lists
.iter()
.filter(|l| {
l.is_cell
&& l.section_index == section_index
&& l.host_para_index == host_para
&& l.control_index == control_index
&& l.grid.is_some_and(|g| g.row as usize == row)
})
.min_by_key(|l| l.grid.map(|g| g.col).unwrap_or(u16::MAX))
.map(|l| l.list_id)
}
pub fn set_text_box_at(
&mut self,
para_in_list: usize,
control_index: usize,
attach: bool,
) -> Result<String, HwpError> {
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let Some(Control::Shape(shape)) = para.controls.get_mut(control_index) else {
return Ok(r#"{"ok":false,"reason":"그리기 개체가 아니다"}"#.to_string());
};
let Some(drawing) = shape.drawing_mut() else {
return Ok(r#"{"ok":false,"reason":"글상자를 담을 수 없는 개체다"}"#.to_string());
};
let changed = if attach {
if drawing.text_box.is_some() {
false
} else {
drawing.text_box = Some(TextBox {
paragraphs: vec![Paragraph::new_empty()],
..Default::default()
});
true
}
} else {
drawing.text_box.take().is_some()
};
if changed {
drawing.sync_text_box_storage_bit();
section.raw_stream = None;
}
Ok(format!("{{\"ok\":{}}}", changed))
}
pub fn attach_caption_at(
&mut self,
para_in_list: usize,
control_index: usize,
) -> Result<String, HwpError> {
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let Some(Control::Shape(shape)) = para.controls.get_mut(control_index) else {
return Ok(r#"{"ok":false,"reason":"그리기 개체가 아니다"}"#.to_string());
};
if Self::shape_caption_slot(shape).is_some() {
return Ok(r#"{"ok":false,"reason":"이미 캡션이 있다"}"#.to_string());
}
let mut caption_para = Paragraph::new_empty();
caption_para.insert_text_at(0, "그림 ");
caption_para.char_offsets = vec![0, 1, 2, 3, 11];
caption_para.controls.push(Control::AutoNumber(AutoNumber {
number_type: AutoNumberType::Picture,
..Default::default()
}));
caption_para.char_count = 12;
*Self::shape_caption_slot(shape) = Some(Caption {
paragraphs: vec![caption_para],
..Default::default()
});
shape.common_mut().attr |= 1 << 29;
section.raw_stream = None;
Ok(r#"{"ok":true,"pos":12}"#.to_string())
}
pub fn detach_caption_at(
&mut self,
para_in_list: usize,
control_index: usize,
) -> Result<String, HwpError> {
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let Some(Control::Shape(shape)) = para.controls.get_mut(control_index) else {
return Ok(r#"{"ok":false,"reason":"그리기 개체가 아니다"}"#.to_string());
};
let had = Self::shape_caption_slot(shape).take().is_some();
if had {
shape.common_mut().attr &= !(1u32 << 29);
section.raw_stream = None;
}
Ok(format!("{{\"ok\":{}}}", had))
}
fn shape_caption_slot(shape: &mut ShapeObject) -> &mut Option<Caption> {
match shape {
ShapeObject::Line(s) => &mut s.drawing.caption,
ShapeObject::Rectangle(s) => &mut s.drawing.caption,
ShapeObject::Ellipse(s) => &mut s.drawing.caption,
ShapeObject::Arc(s) => &mut s.drawing.caption,
ShapeObject::Polygon(s) => &mut s.drawing.caption,
ShapeObject::Curve(s) => &mut s.drawing.caption,
ShapeObject::Group(s) => &mut s.caption,
ShapeObject::Picture(s) => &mut s.caption,
ShapeObject::Chart(s) => &mut s.caption,
ShapeObject::Ole(s) => &mut s.caption,
}
}
pub fn break_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
pos: usize,
kind: &str,
) -> Result<String, HwpError> {
let marker_units = match kind {
"page" | "column" => 0usize,
"colDef" => EXTENDED_CTRL_UNITS,
"section" => 2 * EXTENDED_CTRL_UNITS,
other => return Err(HwpError::InvalidField(format!("모르는 나누기 {}", other))),
};
let (start, end) = {
let para = self
.cursor_paragraph_ref(list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
(leading_anchor_pos(para), stream_len(para))
};
let at_end = pos >= end && end > 0;
let target_in_list = if at_end {
para_in_list + 1
} else if pos <= start {
para_in_list
} else {
let raw = self.split_para_at_cursor(list_id, para_in_list, pos)?;
if raw.contains("\"ok\":false") {
return Ok(raw);
}
para_in_list + 1
};
let at_start = !at_end && target_in_list == para_in_list;
let occupied = self
.cursor_paragraph_ref(list_id, target_in_list)
.map(|p| {
p.column_type != ColumnBreakType::None
|| matches!(
p.controls.first(),
Some(Control::SectionDef(_) | Control::ColumnDef(_))
)
})
.unwrap_or(false);
if occupied {
self.insert_empty_paragraph_at(list_id, target_in_list)?;
}
let caret_para = if at_start && occupied {
target_in_list + 1
} else {
target_in_list
};
let caret_start = self
.cursor_paragraph_ref(list_id, caret_para)
.map(leading_anchor_pos)
.unwrap_or(0);
let caret = marker_units.max(caret_start);
if list_id != ROOT_LIST_ID {
return Ok(format!(
"{{\"ok\":true,\"para\":{},\"pos\":{}}}",
caret_para, caret
));
}
let Some((sec, para)) = root_para_location(self, target_in_list) else {
return Ok(r#"{"ok":false,"reason":"대상 문단이 없다"}"#.to_string());
};
let target = self
.document
.sections
.get_mut(sec)
.and_then(|s| s.paragraphs.get_mut(para))
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", target_in_list)))?;
match kind {
"page" => target.column_type = ColumnBreakType::Page,
"column" => target.column_type = ColumnBreakType::Column,
"colDef" => {
target.column_type = ColumnBreakType::MultiColumn;
target
.controls
.insert(0, Control::ColumnDef(ColumnDef::default()));
target.char_count += EXTENDED_CTRL_UNITS as u32;
}
_ => {
target.column_type = ColumnBreakType::Section;
target
.controls
.insert(0, Control::ColumnDef(ColumnDef::default()));
target
.controls
.insert(0, Control::SectionDef(Box::default()));
target.char_count += 2 * EXTENDED_CTRL_UNITS as u32;
}
}
if let Some(section) = self.document.sections.get_mut(sec) {
section.raw_stream = None;
}
Ok(format!(
"{{\"ok\":true,\"para\":{},\"pos\":{}}}",
caret_para, caret
))
}
pub fn insert_auto_number_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
pos: usize,
kind: &str,
) -> Result<String, HwpError> {
let number_type = match kind {
"page" | "current" => AutoNumberType::Page,
"total" => AutoNumberType::TotalPage,
other => {
return Err(HwpError::InvalidField(format!(
"모르는 번호 갈래 {}",
other
)))
}
};
if list_id != ROOT_LIST_ID {
return Ok(r#"{"ok":false,"reason":"본문 밖은 아직 다루지 않는다"}"#.to_string());
}
let char_idx = {
let para = self
.cursor_paragraph_ref(list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
char_idx_at_stream_pos(para, pos).min(para.text.chars().count())
};
let (sec, para_idx) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
&self.document.sections[sec].paragraphs[para_idx],
);
{
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let para = section
.paragraphs
.get_mut(para_idx)
.ok_or_else(|| HwpError::InvalidField(format!("문단 {} 없음", para_idx)))?;
let control_index = para
.control_text_positions()
.iter()
.filter(|p| **p < char_idx)
.count();
para.insert_text_at(char_idx, " ");
para.controls.insert(
control_index,
Control::AutoNumber(AutoNumber {
number_type,
..Default::default()
}),
);
para.char_count += (EXTENDED_CTRL_UNITS - 1) as u32;
section.raw_stream = None;
}
self.reflow_paragraph(sec, para_idx);
let hwp3_layout = self.document.layout_profile().hwp3_layout();
crate::renderer::composer::recalculate_section_vpos(
&mut self.document.sections[sec].paragraphs,
para_idx,
None,
stored_end_for_reset,
&self.styles,
self.dpi,
hwp3_layout,
);
self.recompose_section(sec);
self.paginate();
Ok(r#"{"ok":true}"#.to_string())
}
pub fn section_starts_json(&self) -> String {
let mut starts: Vec<String> = Vec::new();
let mut para_in_body = 0usize;
for section in self.document.sections.iter() {
for para in section.paragraphs.iter() {
let marks_section = para_in_body == 0
|| matches!(para.controls.first(), Some(Control::SectionDef(_)));
if marks_section {
starts.push(para_in_body.to_string());
}
para_in_body += 1;
}
}
format!("[{}]", starts.join(","))
}
fn insert_empty_paragraph_at(
&mut self,
list_id: u32,
para_in_list: usize,
) -> Result<(), HwpError> {
if list_id != ROOT_LIST_ID {
return Err(HwpError::InvalidField(
"본문 밖에는 아직 문단을 끼우지 않는다".into(),
));
}
let (sec, para) = root_para_location(self, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list)))?;
let section = self
.document
.sections
.get_mut(sec)
.ok_or_else(|| HwpError::InvalidField(format!("구역 {} 없음", sec)))?;
let fresh = match section.paragraphs.get(para) {
Some(neighbor) => Paragraph::new_empty_like(neighbor),
None => Paragraph::new_empty(),
};
section.paragraphs.insert(para, fresh);
section.raw_stream = None;
Ok(())
}
pub fn delete_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
start_pos: usize,
end_pos: usize,
) -> Result<String, HwpError> {
let (start_char, end_char) = {
let para = self
.cursor_paragraph_ref(list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let last = para.text.chars().count();
(
char_idx_at_stream_pos(para, start_pos).min(last),
char_idx_at_stream_pos(para, end_pos).min(last),
)
};
if start_char >= end_char {
return Ok(r#"{"ok":false,"reason":"빈 범위"}"#.to_string());
}
if list_id == ROOT_LIST_ID {
let (sec, para) = root_para_location(self, para_in_list).ok_or_else(|| {
HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list))
})?;
return self.delete_text_native(sec, para, start_char, end_char - start_char);
}
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let path = cell_path_to_list(&lists, list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField("셀 경로를 세울 수 없음".into()))?;
let section_index = entry.section_index;
let host_para = root_para_of(&lists, entry);
self.delete_range_in_cell_by_path(
section_index,
host_para,
&path,
para_in_list,
start_char,
para_in_list,
end_char,
)
}
pub fn table_edit_at_cursor(&mut self, list_id: u32, op: &str) -> Result<String, HwpError> {
let (section, host_para, control_index, row, col) = {
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let grid = entry
.grid
.ok_or_else(|| HwpError::InvalidField("표 셀이 아니다".into()))?;
if entry.host_list_id != ROOT_LIST_ID {
return Ok(r#"{"ok":false,"reason":"중첩 표는 아직 다루지 않는다"}"#.to_string());
}
(
entry.section_index,
entry.host_para_index,
entry.control_index,
grid.row,
grid.col,
)
};
match op {
"insertRowAbove" => {
self.insert_table_row_native(section, host_para, control_index, row, false)
}
"insertRowBelow" | "appendRow" | "appendRowAtEnd" => {
self.insert_table_row_native(section, host_para, control_index, row, true)
}
"insertColLeft" => {
self.insert_table_column_native(section, host_para, control_index, col, false)
}
"insertColRight" => {
self.insert_table_column_native(section, host_para, control_index, col, true)
}
"deleteRow" => self.delete_table_row_native(section, host_para, control_index, row),
"deleteCol" => self.delete_table_column_native(section, host_para, control_index, col),
"splitRow2" => self.split_table_cell_into_native(
section,
host_para,
control_index,
row,
col,
2,
1,
true,
false,
),
"splitCol2" => self.split_table_cell_into_native(
section,
host_para,
control_index,
row,
col,
1,
2,
true,
false,
),
"resizeCellRight" | "resizeCellLeft" | "resizeCellDown" | "resizeCellUp" => {
let dir = op.trim_start_matches("resizeCell");
let vertical = matches!(dir, "Down" | "Up");
let forward = matches!(dir, "Right" | "Down");
self.resize_table_cell_native(
section,
host_para,
control_index,
row,
col,
vertical,
forward,
)
}
"resizeRight" | "resizeLeft" | "resizeDown" | "resizeUp" | "resizeLineRight"
| "resizeLineLeft" | "resizeLineDown" | "resizeLineUp" => {
let line_mode = op.starts_with("resizeLine");
let dir = op
.trim_start_matches("resizeLine")
.trim_start_matches("resize");
let vertical = matches!(dir, "Down" | "Up");
let forward = matches!(dir, "Right" | "Down");
self.resize_table_native(
section,
host_para,
control_index,
row,
col,
vertical,
forward,
line_mode,
)
}
_ => Err(HwpError::InvalidField(format!("모르는 표 편집 '{}'", op))),
}
}
pub fn table_merge_at_cursor(
&mut self,
list_id: u32,
end_row: u16,
end_col: u16,
) -> Result<String, HwpError> {
let (section, host_para, control_index, row, col) = {
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let grid = entry
.grid
.ok_or_else(|| HwpError::InvalidField("표 셀이 아니다".into()))?;
if entry.host_list_id != ROOT_LIST_ID {
return Ok(r#"{"ok":false,"reason":"중첩 표는 아직 다루지 않는다"}"#.to_string());
}
(
entry.section_index,
entry.host_para_index,
entry.control_index,
grid.row,
grid.col,
)
};
self.merge_table_cells_native(
section,
host_para,
control_index,
row.min(end_row),
col.min(end_col),
row.max(end_row),
col.max(end_col),
)
}
pub fn clear_table_cells_at_cursor(
&mut self,
list_id: u32,
end_row: u16,
end_col: u16,
) -> Result<String, HwpError> {
let (section, host_para, control_index, row, col) = {
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let grid = entry
.grid
.ok_or_else(|| HwpError::InvalidField("표 셀이 아니다".into()))?;
if entry.host_list_id != ROOT_LIST_ID {
return Ok(r#"{"ok":false,"reason":"중첩 표는 아직 다루지 않는다"}"#.to_string());
}
(
entry.section_index,
entry.host_para_index,
entry.control_index,
grid.row,
grid.col,
)
};
let (r1, r2) = (row.min(end_row), row.max(end_row));
let (c1, c2) = (col.min(end_col), col.max(end_col));
let table = self.get_table_mut(section, host_para, control_index)?;
let mut cleared = false;
for cell in table.cells.iter_mut() {
if cell.row < r1 || cell.row > r2 || cell.col < c1 || cell.col > c2 {
continue;
}
cell.paragraphs.truncate(1);
let Some(para) = cell.paragraphs.first_mut() else {
continue;
};
if para.text.is_empty() && para.controls.is_empty() {
continue; }
cleared = true;
para.text.clear();
para.char_count = 1;
para.char_offsets.clear();
para.char_shapes.truncate(1);
if let Some(first) = para.char_shapes.first_mut() {
first.start_pos = 0;
}
para.range_tags.clear();
para.line_segs.clear();
para.tab_extended.clear();
para.controls.clear();
para.has_para_text = false;
}
if cleared {
self.document.sections[section].raw_stream = None;
self.mark_cell_control_dirty(section, host_para, control_index);
self.mark_section_dirty(section);
self.paginate_if_needed();
}
Ok(format!(r#"{{"ok":true,"cleared":{}}}"#, cleared))
}
pub fn para_bounds_json(&self, list_id: u32, para_in_list: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "{}".to_string();
};
format!(
"{{\"start\":{},\"end\":{},\"selectStart\":{}}}",
leading_anchor_pos(para),
stream_len(para),
select_start_pos(para),
)
}
pub fn line_starts_json(&self, list_id: u32, para_in_list: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "[]".to_string();
};
let starts: Vec<String> = para
.line_segs
.iter()
.map(|seg| seg.text_start.to_string())
.collect();
format!("[{}]", starts.join(","))
}
pub fn word_end_json(&self, list_id: u32, para_in_list: usize, pos: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "null".to_string();
};
word_end_from(para, pos).to_string()
}
pub fn word_starts_json(&self, list_id: u32, para_in_list: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "[]".to_string();
};
let starts: Vec<String> = word_starts(para).iter().map(|p| p.to_string()).collect();
format!("[{}]", starts.join(","))
}
pub fn caret_stops_json(&self, list_id: u32, para_in_list: usize) -> String {
let Some(para) = self.cursor_paragraph_ref(list_id, para_in_list) else {
return "[]".to_string();
};
let stops: Vec<String> = caret_stops(para).iter().map(|p| p.to_string()).collect();
format!("[{}]", stops.join(","))
}
pub fn apply_para_format_at_cursor(
&mut self,
list_id: u32,
para_in_list: usize,
props_json: &str,
) -> Result<String, HwpError> {
if list_id == ROOT_LIST_ID {
let (sec, para) = root_para_location(self, para_in_list).ok_or_else(|| {
HwpError::InvalidField(format!("본문 문단 {} 없음", para_in_list))
})?;
return self.apply_para_format_native(sec, para, props_json);
}
let (_, lists) = self.collect_fields_and_lists();
let entry = lists
.iter()
.find(|l| l.list_id == list_id)
.ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
let path = cell_path_to_list(&lists, list_id, para_in_list)
.ok_or_else(|| HwpError::InvalidField("셀 경로를 세울 수 없음".into()))?;
if path.len() != 1 {
return Err(HwpError::InvalidField(
"중첩 셀의 문단 서식은 아직 다루지 않는다".into(),
));
}
let (control_idx, cell_idx, cell_para_idx) = path[0];
let section_index = entry.section_index;
let host_para = root_para_of(&lists, entry);
self.apply_para_format_in_cell_native(
section_index,
host_para,
control_idx,
cell_idx,
cell_para_idx,
props_json,
)
}
fn cursor_paragraph_ref(&self, list_id: u32, para_in_list: usize) -> Option<&Paragraph> {
if list_id == ROOT_LIST_ID {
let (sec, para) = root_para_location(self, para_in_list)?;
return self.document.sections.get(sec)?.paragraphs.get(para);
}
let (_, lists) = self.collect_fields_and_lists();
cursor_paragraph(self, &lists, list_id, para_in_list)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::document::Section;
use crate::model::style::ParaShape;
fn render_tree_contains_text(
node: &crate::renderer::render_tree::RenderNode,
needle: &str,
) -> bool {
matches!(
&node.node_type,
crate::renderer::render_tree::RenderNodeType::TextRun(run)
if run.text.contains(needle)
) || node
.children
.iter()
.any(|child| render_tree_contains_text(child, needle))
}
fn first_table_cell_width(
node: &crate::renderer::render_tree::RenderNode,
model_cell_index: u32,
) -> Option<f64> {
if matches!(
&node.node_type,
crate::renderer::render_tree::RenderNodeType::TableCell(cell)
if cell.model_cell_index == Some(model_cell_index)
) {
return Some(node.bbox.width);
}
node.children
.iter()
.find_map(|child| first_table_cell_width(child, model_cell_index))
}
fn clearing_table_cells_invalidates_measurement_and_page_tree_owners() {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().expect("blank document");
let created = core
.create_table_native(0, 0, 0, 1, 1)
.expect("single-cell table");
let created: serde_json::Value = serde_json::from_str(&created).expect("table result");
let host_para = created["paraIdx"].as_u64().expect("table paragraph") as usize;
let control_index = created["controlIdx"].as_u64().expect("table control") as usize;
core.insert_text_in_cell_native(0, host_para, control_index, 0, 0, 0, "CLEAR-ME")
.expect("cell text");
let before = core.build_page_tree_cached(0).expect("cached page tree");
assert!(render_tree_contains_text(&before.root, "CLEAR-ME"));
let (_, lists) = core.collect_fields_and_lists();
let list_id = lists
.iter()
.find(|entry| {
entry.host_para_index == host_para
&& entry.control_index == control_index
&& entry
.grid
.is_some_and(|grid| grid.row == 0 && grid.col == 0)
})
.expect("cell list")
.list_id;
let result = core
.clear_table_cells_at_cursor(list_id, 0, 0)
.expect("clear cell contents");
assert!(result.contains("\"cleared\":true"), "{result}");
let after = core.build_page_tree_cached(0).expect("rebuilt page tree");
assert!(
!render_tree_contains_text(&after.root, "CLEAR-ME"),
"the pre-clear cached page must not survive"
);
}
fn cursor_cell_resize_invalidates_cached_table_geometry() {
let mut core = DocumentCore::new_empty();
core.create_blank_document_native().expect("blank document");
let created = core
.create_table_native(0, 0, 0, 1, 2)
.expect("two-cell table");
let created: serde_json::Value = serde_json::from_str(&created).expect("table result");
let host_para = created["paraIdx"].as_u64().expect("table paragraph") as usize;
let control_index = created["controlIdx"].as_u64().expect("table control") as usize;
let (_, lists) = core.collect_fields_and_lists();
let list_id = lists
.iter()
.find(|entry| {
entry.host_para_index == host_para
&& entry.control_index == control_index
&& entry
.grid
.is_some_and(|grid| grid.row == 0 && grid.col == 0)
})
.expect("first cell list")
.list_id;
let before = core.build_page_tree_cached(0).expect("cached table tree");
let before_width = first_table_cell_width(&before.root, 0).expect("first cell bbox");
let result = core
.table_edit_at_cursor(list_id, "resizeCellRight")
.expect("cell boundary resize");
assert!(result.contains("\"moved\":true"), "{result}");
let after = core.build_page_tree_cached(0).expect("rebuilt table tree");
let after_width = first_table_cell_width(&after.root, 0).expect("first cell bbox");
assert!(
(after_width - before_width).abs() > 0.1,
"cached geometry survived source resize: {before_width} -> {after_width}"
);
}
#[test]
fn para_shape_set_uses_hwp_codes() {
clearing_table_cells_invalidates_measurement_and_page_tree_owners();
cursor_cell_resize_invalidates_cached_table_geometry();
let mut core = DocumentCore::new_empty();
core.document.doc_info.para_shapes = vec![ParaShape {
alignment: Alignment::Center,
line_spacing_type: LineSpacingType::Percent,
line_spacing: 160,
margin_left: 100,
head_type: HeadType::Outline,
para_level: 2,
..Default::default()
}];
core.document.sections.push(Section {
paragraphs: vec![Paragraph {
para_shape_id: 0,
..Default::default()
}],
..Default::default()
});
let json = core.para_shape_set_json(ROOT_LIST_ID, 0);
assert!(json.contains("\"AlignType\":3"), "{json}");
assert!(json.contains("\"LineSpacingType\":0"), "{json}");
assert!(json.contains("\"LineSpacing\":160"), "{json}");
assert!(json.contains("\"LeftMargin\":100"), "{json}");
assert!(json.contains("\"HeadingType\":1"), "{json}");
assert!(json.contains("\"Level\":2"), "{json}");
}
#[test]
fn missing_cursor_gives_empty_set() {
auto_number_insertion_publishes_the_new_wrap_before_render_and_save();
let core = DocumentCore::new_empty();
assert_eq!(core.para_shape_set_json(ROOT_LIST_ID, 99), "{}");
assert_eq!(core.char_shape_set_json(ROOT_LIST_ID, 99, 0), "{}");
}
fn auto_number_insertion_publishes_the_new_wrap_before_render_and_save() {
let text = "A".repeat(20);
let mut paragraph = Paragraph {
text: text.clone(),
char_offsets: (0..text.chars().count() as u32).collect(),
char_count: text.chars().count() as u32 + 1,
char_shapes: vec![crate::model::paragraph::CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}],
..Default::default()
};
let styles = crate::renderer::style_resolver::ResolvedStyleSet::default();
let composed = crate::renderer::composer::compose_paragraph(¶graph);
let measured =
crate::renderer::composer::estimate_composed_line_width(&composed.lines[0], &styles);
let width_hwp = crate::renderer::px_to_hwpunit(measured + 1.0, 96.0).max(1);
paragraph.line_segs = vec![crate::model::paragraph::LineSeg {
text_start: 0,
line_height: 1_000,
segment_width: width_hwp,
tag: crate::model::paragraph::LineSeg::TAG_SINGLE_SEGMENT_LINE,
..Default::default()
}];
let mut core = DocumentCore::new_empty();
core.document.sections = vec![Section {
section_def: crate::model::document::SectionDef {
page_def: crate::model::page::PageDef {
width: width_hwp as u32,
height: 84_188,
margin_left: 0,
margin_right: 0,
margin_top: 0,
margin_bottom: 0,
margin_header: 0,
margin_footer: 0,
margin_gutter: 0,
..Default::default()
},
..Default::default()
},
paragraphs: vec![paragraph],
..Default::default()
}];
core.styles = styles;
core.composed = vec![Vec::new()];
core.dirty_sections = vec![true];
core.dirty_paragraphs = vec![None];
core.recompose_section(0);
core.paginate();
core.insert_auto_number_at_cursor(ROOT_LIST_ID, 0, 10, "page")
.expect("auto number insertion succeeds");
let paragraph = &core.document.sections[0].paragraphs[0];
assert!(paragraph.line_segs.len() > 1);
assert!(!paragraph.stored_text_partition_is_dirty());
assert!(!core.pagination.is_empty());
let bytes = crate::serializer::body_text::serialize_section(&core.document.sections[0]);
let parsed = crate::parser::body_text::parse_body_text_section(&bytes).unwrap();
assert_eq!(
parsed.paragraphs[0].line_segs.len(),
paragraph.line_segs.len()
);
}
#[test]
fn text_file_formats_keep_distinct_encoding_contracts() {
let source = "가◦€";
assert_eq!(escape_outside_cp949(source), "가◦€");
assert_eq!(json_escape(source), "\"가◦€\"");
assert_eq!(json_escape(&escape_outside_cp949(source)), "\"가◦€\"");
}
mod z_order {
use super::*;
use crate::model::shape::{RectangleShape, TextWrap};
fn core_with_three() -> DocumentCore {
let mut core = DocumentCore::new_empty();
let controls = (0..3)
.map(|z| {
let mut r = RectangleShape::default();
r.common.z_order = z;
Control::Shape(Box::new(ShapeObject::Rectangle(r)))
})
.collect();
core.document.sections.push(Section {
paragraphs: vec![Paragraph {
controls,
..Default::default()
}],
..Default::default()
});
core
}
fn orders(core: &DocumentCore) -> Vec<i32> {
core.document.sections[0].paragraphs[0]
.controls
.iter()
.filter_map(control_common)
.map(|c| c.z_order)
.collect()
}
#[test]
fn bring_to_front_pushes_the_rest_down() {
let mut core = core_with_three();
core.set_control_z_order_at(0, 0, "front").unwrap();
assert_eq!(orders(&core), vec![2, 0, 1]);
}
#[test]
fn send_to_back_pulls_the_rest_up() {
let mut core = core_with_three();
core.set_control_z_order_at(0, 2, "back").unwrap();
assert_eq!(orders(&core), vec![1, 2, 0]);
}
#[test]
fn one_step_swaps_with_the_neighbour() {
let mut core = core_with_three();
core.set_control_z_order_at(0, 0, "forward").unwrap();
assert_eq!(orders(&core), vec![1, 0, 2]);
let mut core = core_with_three();
core.set_control_z_order_at(0, 2, "backward").unwrap();
assert_eq!(orders(&core), vec![0, 2, 1]);
let mut core = core_with_three();
let out = core.set_control_z_order_at(0, 2, "forward").unwrap();
assert_eq!(orders(&core), vec![0, 1, 2]);
assert!(out.contains("\"moved\":false"), "{out}");
}
#[test]
fn resize_settles_the_shape_component_too() {
let mut core = core_with_three();
match &mut core.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => {
let c = s.common_mut();
c.width = 8475;
c.height = 6750;
let a = s.shape_attr_mut();
a.original_width = 8475;
a.current_width = 8475;
a.original_height = 6750;
a.current_height = 6750;
a.raw_rendering = vec![1, 2, 3];
}
_ => unreachable!(),
}
core.resize_control_at(0, 0, 283, 0).unwrap();
match &core.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => {
let a = s.shape_attr();
assert_eq!(a.current_width, 8758);
assert!(
(a.render_sx - 8758.0 / 8475.0).abs() < 1e-12,
"{}",
a.render_sx
);
assert_eq!(a.rotation_center.x, 4379, "cur/2 — 실측 4237→4379");
assert!(a.raw_rendering.is_empty(), "행렬 원본을 비워야 재생성된다");
}
_ => unreachable!(),
}
}
#[test]
fn flip_matrix_follows_the_measured_formula() {
let mut core = core_with_three();
let sa = |c: &DocumentCore| match &c.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => {
let a = s.shape_attr();
(a.flip, a.horz_flip, a.render_sx, a.render_tx)
}
_ => unreachable!(),
};
match &mut core.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => {
let a = s.shape_attr_mut();
a.original_width = 8475;
a.current_width = 8475;
}
_ => unreachable!(),
}
core.set_control_flip_at(0, 0, false, false).unwrap();
assert_eq!(sa(&core), (0x01, true, -1.0, 8474.0));
core.set_control_flip_at(0, 0, false, true).unwrap();
assert_eq!(sa(&core), (0x00, false, 1.0, 0.0));
let out = core.set_control_flip_at(0, 0, false, true).unwrap();
assert!(out.contains("\"moved\":false"), "{out}");
match &mut core.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => s.shape_attr_mut().current_width = 8758,
_ => unreachable!(),
}
core.set_control_flip_at(0, 0, false, false).unwrap();
let (_, on, sx, tx) = sa(&core);
assert!(on);
assert_eq!(tx, 8756.0);
assert!((sx - (-(8758.0 / 8475.0))).abs() < 1e-12, "{sx}");
match &mut core.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => {
let a = s.shape_attr_mut();
a.original_height = 6750;
a.current_height = 7033;
}
_ => unreachable!(),
}
core.set_control_flip_at(0, 0, true, false).unwrap();
let ty = match &core.document.sections[0].paragraphs[0].controls[0] {
Control::Shape(s) => s.shape_attr().render_ty,
_ => unreachable!(),
};
assert_eq!(ty, 7034.0);
}
#[test]
fn text_wrap_modes_do_not_touch_the_order() {
let mut core = core_with_three();
core.set_control_z_order_at(0, 1, "behindText").unwrap();
assert_eq!(orders(&core), vec![0, 1, 2]);
let common = control_common(&core.document.sections[0].paragraphs[0].controls[1]);
assert_eq!(common.map(|c| c.text_wrap), Some(TextWrap::BehindText));
core.set_control_z_order_at(0, 1, "inFrontOfText").unwrap();
let common = control_common(&core.document.sections[0].paragraphs[0].controls[1]);
assert_eq!(common.map(|c| c.text_wrap), Some(TextWrap::InFrontOfText));
}
}
}