use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;
fn not_an_equation_error(ctrl: &Control) -> HwpError {
if let Control::Shape(shape) = ctrl {
if matches!(shape.as_ref(), crate::model::shape::ShapeObject::Ole(_)) {
return HwpError::RenderError(
"지정된 컨트롤은 OLE 개체입니다 — 한/글 5.x·97 계열이 저장한 수식을 포함해 \
OLE 개체는 먼저 native 수식으로 변환해야 내용을 편집할 수 있습니다(#7105). \
개체 삭제·이동은 도형 명령(delete-control · delete-shape)을 쓰십시오."
.to_string(),
);
}
}
HwpError::RenderError("지정된 컨트롤이 수식이 아닙니다".to_string())
}
impl DocumentCore {
pub fn promote_ole_equation_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
) -> Result<String, HwpError> {
use crate::model::control::Equation;
use crate::model::shape::ShapeObject;
use crate::parser::tags::CTRL_EQUATION;
let (mut common, bin_data_id) = {
let section = self.document.sections.get(section_idx).ok_or_else(|| {
HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
})?;
let paragraph = section.paragraphs.get(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
let control = paragraph.controls.get(control_idx).ok_or_else(|| {
HwpError::RenderError(format!("컨트롤 인덱스 {} 범위 초과", control_idx))
})?;
let Control::Shape(shape) = control else {
return Err(HwpError::RenderError(
"지정된 컨트롤이 OLE 수식이 아닙니다".to_string(),
));
};
let ShapeObject::Ole(ole) = shape.as_ref() else {
return Err(HwpError::RenderError(
"지정된 컨트롤이 OLE 수식이 아닙니다".to_string(),
));
};
(ole.common.clone(), ole.bin_data_id)
};
let ole_bytes = crate::renderer::layout::find_bin_data(
&self.document.bin_data_content,
u16::try_from(bin_data_id).map_err(|_| {
HwpError::RenderError("OLE BinData 참조가 허용 범위를 벗어났습니다".to_string())
})?,
)
.and_then(|content| {
content
.data
.load_limited(crate::model::bin_data::MAX_BIN_DATA_BYTES)
})
.ok_or_else(|| HwpError::RenderError("OLE 수식 BinData를 읽을 수 없습니다".to_string()))?;
let legacy_script = crate::parser::ole_container::parse_ole_container(&ole_bytes)
.and_then(|container| container.raw_contents)
.and_then(|contents| {
crate::parser::ole_container::parse_equation_contents_script(&contents)
})
.ok_or_else(|| {
HwpError::RenderError(
"지정된 OLE 개체는 편집 가능한 한/글 수식이 아닙니다".to_string(),
)
})?;
let script = crate::renderer::equation::legacy_hwpeq::normalize(&legacy_script)
.unwrap_or(legacy_script);
let (_, base_height) = crate::renderer::equation::intrinsic_size_hwp(&script, 1000);
let font_size = if base_height > 0 && common.height > 0 {
((u64::from(common.height) * 1000) / u64::from(base_height)).clamp(200, 40_000) as u32
} else {
1000
};
common.ctrl_id = CTRL_EQUATION;
if common.description.is_empty() {
common.description = "레거시 OLE 수식에서 변환한 수식입니다.".to_string();
}
let equation = Equation {
common,
script: script.clone(),
font_size,
color: 0,
baseline: 85,
version_info: "Equation Version 60".to_string(),
font_name: "HYhwpEQ".to_string(),
..Default::default()
};
let section = &mut self.document.sections[section_idx];
let paragraph = &mut section.paragraphs[parent_para_idx];
paragraph.align_ctrl_data_records();
paragraph.controls[control_idx] = Control::Equation(Box::new(equation));
if control_idx < paragraph.ctrl_data_records.len() {
paragraph.ctrl_data_records[control_idx] = None;
}
section.raw_stream = None;
self.reflow_paragraph(section_idx, parent_para_idx);
self.recompose_section(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
Ok(format!(
"{{\"ok\":true,\"paraIdx\":{},\"controlIdx\":{},\"script\":\"{}\"}}",
parent_para_idx,
control_idx,
crate::document_core::helpers::json_escape(&script),
))
}
fn find_equation_ref(
&self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: Option<usize>,
cell_para_idx: Option<usize>,
) -> Result<&crate::model::control::Equation, HwpError> {
let section = self.document.sections.get(section_idx).ok_or_else(|| {
HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
})?;
let ctrl = if let (Some(ci), Some(cpi)) = (cell_idx, cell_para_idx) {
let para = section.paragraphs.get(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
let table = match para.controls.get(control_idx) {
Some(Control::Table(t)) => t,
_ => {
return Err(HwpError::RenderError(
"지정된 컨트롤이 표가 아닙니다".to_string(),
))
}
};
let cell = table
.cells
.get(ci)
.ok_or_else(|| HwpError::RenderError(format!("셀 인덱스 {} 범위 초과", ci)))?;
let cell_para = cell.paragraphs.get(cpi).ok_or_else(|| {
HwpError::RenderError(format!("셀 문단 인덱스 {} 범위 초과", cpi))
})?;
cell_para
.controls
.iter()
.find(|c| matches!(c, Control::Equation(_)))
.ok_or_else(|| {
HwpError::RenderError("셀 문단에 수식 컨트롤이 없습니다".to_string())
})?
} else {
let para = section.paragraphs.get(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
para.controls.get(control_idx).ok_or_else(|| {
HwpError::RenderError(format!("컨트롤 인덱스 {} 범위 초과", control_idx))
})?
};
match ctrl {
Control::Equation(e) => Ok(e),
other => Err(not_an_equation_error(other)),
}
}
fn find_equation_mut(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: Option<usize>,
cell_para_idx: Option<usize>,
) -> Result<&mut crate::model::control::Equation, HwpError> {
let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
})?;
let ctrl = if let (Some(ci), Some(cpi)) = (cell_idx, cell_para_idx) {
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(control_idx) {
Some(Control::Table(t)) => t,
_ => {
return Err(HwpError::RenderError(
"지정된 컨트롤이 표가 아닙니다".to_string(),
))
}
};
let cell = table
.cells
.get_mut(ci)
.ok_or_else(|| HwpError::RenderError(format!("셀 인덱스 {} 범위 초과", ci)))?;
let cell_para = cell.paragraphs.get_mut(cpi).ok_or_else(|| {
HwpError::RenderError(format!("셀 문단 인덱스 {} 범위 초과", cpi))
})?;
cell_para
.controls
.iter_mut()
.find(|c| matches!(c, Control::Equation(_)))
.ok_or_else(|| {
HwpError::RenderError("셀 문단에 수식 컨트롤이 없습니다".to_string())
})?
} else {
let para = section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
})?;
para.controls.get_mut(control_idx).ok_or_else(|| {
HwpError::RenderError(format!("컨트롤 인덱스 {} 범위 초과", control_idx))
})?
};
match ctrl {
Control::Equation(e) => Ok(e),
other => Err(not_an_equation_error(other)),
}
}
pub(crate) fn equation_properties_json(eq: &crate::model::control::Equation) -> String {
let common_json = Self::common_obj_attr_to_json(&eq.common);
let script_escaped = crate::document_core::helpers::json_escape(&eq.script);
let font_name_escaped = crate::document_core::helpers::json_escape(&eq.font_name);
format!(
concat!(
"{{{},\"script\":\"{}\",\"fontSize\":{},\"color\":{},",
"\"baseline\":{},\"fontName\":\"{}\",",
"\"hasCaption\":false,\"captionDirection\":\"None\",",
"\"captionWidth\":0,\"captionSpacing\":0}}"
),
common_json, script_escaped, eq.font_size, eq.color, eq.baseline, font_name_escaped,
)
}
pub(crate) fn apply_equation_properties(
eq: &mut crate::model::control::Equation,
_dpi: f64,
props_json: &str,
) {
use crate::document_core::helpers::{json_i32, json_str, json_u32};
let script_before = eq.script.clone();
let font_size_before = eq.font_size;
if let Some(s) = json_str(props_json, "script") {
eq.script = s;
}
if let Some(fs) = json_u32(props_json, "fontSize") {
eq.font_size = fs;
}
if let Some(c) = json_u32(props_json, "color") {
eq.color = c;
}
if let Some(bl) = json_i32(props_json, "baseline") {
eq.baseline = bl as i16;
}
if let Some(fn_) = json_str(props_json, "fontName") {
eq.font_name = fn_;
}
Self::apply_common_obj_attr_from_json(&mut eq.common, props_json);
let explicit_width = json_u32(props_json, "width").is_some();
let explicit_height = json_u32(props_json, "height").is_some();
let size_driver_changed = eq.script != script_before || eq.font_size != font_size_before;
if size_driver_changed && (!explicit_width || !explicit_height) {
let (width, height) = crate::renderer::equation::edited_size_hwp(eq);
if !explicit_width {
eq.common.width = width;
}
if !explicit_height {
eq.common.height = height;
}
}
if eq.raw_ctrl_seal.is_none() {
eq.raw_ctrl_data.clear();
}
}
pub fn get_equation_properties_native(
&self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: Option<usize>,
cell_para_idx: Option<usize>,
) -> Result<String, HwpError> {
let eq = self.find_equation_ref(
section_idx,
parent_para_idx,
control_idx,
cell_idx,
cell_para_idx,
)?;
Ok(Self::equation_properties_json(eq))
}
pub fn set_equation_properties_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
cell_idx: Option<usize>,
cell_para_idx: Option<usize>,
props_json: &str,
) -> Result<String, HwpError> {
let dpi = self.dpi;
let eq = self.find_equation_mut(
section_idx,
parent_para_idx,
control_idx,
cell_idx,
cell_para_idx,
)?;
let previous_flow = (
eq.common.treat_as_char,
crate::renderer::equation::flow_metrics_hwp(eq),
(
eq.common.margin.left,
eq.common.margin.right,
eq.common.margin.top,
eq.common.margin.bottom,
),
eq.common.affect_line_spacing,
);
Self::apply_equation_properties(eq, dpi, props_json);
let current_flow = (
eq.common.treat_as_char,
crate::renderer::equation::flow_metrics_hwp(eq),
(
eq.common.margin.left,
eq.common.margin.right,
eq.common.margin.top,
eq.common.margin.bottom,
),
eq.common.affect_line_spacing,
);
let inline_flow_changed =
(previous_flow.0 || current_flow.0) && previous_flow != current_flow;
if inline_flow_changed {
if let (Some(cell), Some(paragraph)) = (cell_idx, cell_para_idx) {
self.reflow_cell_paragraph(
section_idx,
parent_para_idx,
control_idx,
cell,
paragraph,
);
} else {
let stored_end = crate::renderer::composer::paragraph_flow_end(
&self.document.sections[section_idx].paragraphs[parent_para_idx],
);
self.reflow_paragraph(section_idx, parent_para_idx);
let hwp3_layout = self.document.layout_profile().hwp3_layout();
crate::renderer::composer::recalculate_section_vpos(
&mut self.document.sections[section_idx].paragraphs,
parent_para_idx,
None,
stored_end,
&self.styles,
self.dpi,
hwp3_layout,
);
}
}
if cell_idx.is_some() {
self.mark_cell_control_dirty(section_idx, parent_para_idx, control_idx);
}
let section = &mut self.document.sections[section_idx];
section.raw_stream = None;
self.recompose_section(section_idx);
self.paginate_if_needed();
Ok(crate::document_core::helpers::json_ok())
}
pub fn render_equation_preview_native(
&self,
script: &str,
font_size_hwpunit: u32,
color: u32,
) -> Result<String, HwpError> {
use crate::renderer::equation::document_script::tokenize;
use crate::renderer::equation::layout::EqLayout;
use crate::renderer::equation::parser::EqParser;
use crate::renderer::equation::svg_render::{eq_color_to_svg, render_equation_svg};
let font_size_px = crate::renderer::hwpunit_to_px(font_size_hwpunit as i32, self.dpi);
let tokens = tokenize(script);
let ast = EqParser::for_document(tokens).parse();
let layout_box = EqLayout::new(font_size_px).layout(&ast);
let color_str = eq_color_to_svg(color);
let svg_fragment = render_equation_svg(&layout_box, &color_str, font_size_px);
let w = layout_box.width;
let h = layout_box.height;
let svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {:.2} {:.2}\" width=\"{:.2}\" height=\"{:.2}\">{}</svg>",
w, h, w, h, svg_fragment,
);
Ok(svg)
}
pub fn delete_equation_control_native(
&mut self,
section_idx: usize,
parent_para_idx: usize,
control_idx: usize,
) -> Result<String, HwpError> {
if section_idx >= self.document.sections.len() {
return Err(HwpError::RenderError(format!(
"구역 인덱스 {} 범위 초과",
section_idx
)));
}
let section = &mut self.document.sections[section_idx];
if parent_para_idx >= section.paragraphs.len() {
return Err(HwpError::RenderError(format!(
"문단 인덱스 {} 범위 초과",
parent_para_idx
)));
}
let para = &mut section.paragraphs[parent_para_idx];
if control_idx >= para.controls.len() {
return Err(HwpError::RenderError(format!(
"컨트롤 인덱스 {} 범위 초과",
control_idx
)));
}
if !matches!(¶.controls[control_idx], Control::Equation(_)) {
return Err(not_an_equation_error(¶.controls[control_idx]));
}
para.remove_control(control_idx);
Self::reflow_paragraph_line_segs_after_control_delete(para, &self.styles, self.dpi);
section.raw_stream = None;
self.recompose_section(section_idx);
self.paginate_if_needed();
self.event_log.push(DocumentEvent::PictureDeleted {
section: section_idx,
para: parent_para_idx,
ctrl: control_idx,
});
Ok("{\"ok\":true}".to_string())
}
pub fn insert_equation_native(
&mut self,
section_idx: usize,
para_idx: usize,
char_offset: usize,
script: &str,
font_size: u32,
color: u32,
) -> Result<String, HwpError> {
use crate::model::control::Equation;
use crate::model::shape::{CommonObjAttr, HorzRelTo, TextWrap, VertRelTo};
use crate::parser::tags::CTRL_EQUATION;
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
)));
}
let (width, height) = crate::renderer::equation::intrinsic_size_hwp(script, font_size);
let equation_order = self.document.sections[section_idx]
.paragraphs
.iter()
.flat_map(|paragraph| paragraph.controls.iter())
.filter(|control| matches!(control, Control::Equation(_)))
.count() as u32;
let equation_instance_order = self
.document
.sections
.iter()
.flat_map(|section| section.paragraphs.iter())
.flat_map(|paragraph| paragraph.controls.iter())
.filter(|control| matches!(control, Control::Equation(_)))
.count();
let equation_instance_sequence = u32::try_from(equation_instance_order)
.ok()
.and_then(|order| order.checked_add(1))
.filter(|&order| order <= 0x03ff_ffff)
.ok_or_else(|| {
HwpError::RenderError("수식 instance ID를 더 이상 배정할 수 없습니다.".to_string())
})?;
let instance_id = 0x4400_0000 | equation_instance_sequence;
let equation = Equation {
common: CommonObjAttr {
ctrl_id: CTRL_EQUATION,
attr: 0x0C2A_2311,
numbering_type: crate::model::shape::ObjectNumberingType::Equation,
treat_as_char: true,
width,
height,
z_order: equation_order as i32,
margin: crate::model::Padding {
left: 56,
right: 56,
top: 0,
bottom: 0,
},
instance_id,
flow_with_text: true,
vert_rel_to: VertRelTo::Para,
horz_rel_to: HorzRelTo::Para,
text_wrap: TextWrap::TopAndBottom,
description: "수식입니다.".to_string(),
..Default::default()
},
script: script.to_string(),
font_size,
color,
baseline: 85,
version_info: "Equation Version 60".to_string(),
font_name: "HYhwpEQ".to_string(),
..Default::default()
};
self.document.sections[section_idx].raw_stream = None;
let paragraph = &mut self.document.sections[section_idx].paragraphs[para_idx];
let insert_idx = {
let positions = crate::document_core::helpers::find_control_text_positions(paragraph);
let mut idx = paragraph.controls.len();
for (i, &pos) in positions.iter().enumerate() {
if pos > char_offset {
idx = i;
break;
}
}
idx
};
paragraph.align_ctrl_data_records();
paragraph
.controls
.insert(insert_idx, Control::Equation(Box::new(equation)));
paragraph.ctrl_data_records.insert(insert_idx, None);
paragraph.shift_for_inline_control_insert(insert_idx, char_offset);
paragraph.char_count += 8;
paragraph.control_mask |= 1u32 << 11;
paragraph.has_para_text = true;
self.shift_active_field_for_control_insert(section_idx, para_idx, insert_idx);
self.reflow_paragraph(section_idx, para_idx);
self.recompose_section(section_idx);
self.paginate_if_needed();
self.invalidate_page_tree_cache();
self.event_log.push(DocumentEvent::PictureInserted {
section: section_idx,
para: para_idx,
});
Ok(format!(
"{{\"ok\":true,\"paraIdx\":{},\"controlIdx\":{}}}",
para_idx, insert_idx
))
}
}
#[cfg(test)]
mod tests {
use crate::document_core::DocumentCore;
use crate::model::control::Equation;
#[test]
fn apply_equation_properties_clears_unsealed_raw_ctrl_data() {
let mut eq = Equation {
script: "1 over 2".to_string(),
font_size: 1000,
raw_ctrl_data: vec![0xAB; 16],
..Default::default()
};
assert!(eq.raw_ctrl_seal.is_none(), "합성 IR 은 봉인이 없다");
DocumentCore::apply_equation_properties(&mut eq, 96.0, r#"{"width":5000,"height":4000}"#);
assert!(
eq.raw_ctrl_data.is_empty(),
"봉인 없는 raw_ctrl_data 는 비워져야 편집이 .hwp 저장에 반영된다"
);
}
}