use crate::document_core::helpers::json_escape as escape_json;
use crate::document_core::DocumentCore;
use crate::model::control::{Control, FormType};
use crate::model::table::Table;
use crate::renderer::render_tree::{FormObjectNode, RenderNode, RenderNodeType};
impl DocumentCore {
pub fn get_form_object_at_native(
&self,
page_num: u32,
x: f64,
y: f64,
) -> Result<String, crate::error::HwpError> {
let tree = self.build_page_tree_cached(page_num)?;
if let Some((form, bbox)) = find_form_node_at(&tree.root, x, y) {
let form_type_str = form_type_to_str(form.form_type);
let cell_loc_json = if let Some((tpi, tci, ci_idx, cp_idx)) = form.cell_location {
format!(
r#","inCell":true,"tablePara":{},"tableCi":{},"cellIdx":{},"cellPara":{}"#,
tpi, tci, ci_idx, cp_idx
)
} else {
String::new()
};
let (ret_para, ret_ci) = if let Some((tpi, _tci, _ci_idx, _cp_idx)) = form.cell_location
{
(tpi, form.control_index)
} else {
(form.para_index, form.control_index)
};
Ok(format!(
r#"{{"found":true,"sec":{},"para":{},"ci":{},"formType":"{}","name":"{}","value":{},"caption":"{}","text":"{}","bbox":{{"x":{},"y":{},"w":{},"h":{}}}{}}}"#,
form.section_index,
ret_para,
ret_ci,
form_type_str,
escape_json(&form.name),
form.value,
escape_json(&form.caption),
escape_json(&form.text),
bbox.0,
bbox.1,
bbox.2,
bbox.3,
cell_loc_json,
))
} else {
Ok(r#"{"found":false}"#.to_string())
}
}
pub fn get_form_value_native(
&self,
sec: usize,
para: usize,
ci: usize,
) -> Result<String, crate::error::HwpError> {
let control = self
.document
.sections
.get(sec)
.and_then(|s| s.paragraphs.get(para))
.and_then(|p| p.controls.get(ci));
match control {
Some(Control::Form(f)) => {
let form_type_str = form_type_to_str(f.form_type);
Ok(format!(
r#"{{"ok":true,"formType":"{}","name":"{}","value":{},"text":"{}","caption":"{}","enabled":{}}}"#,
form_type_str,
escape_json(&f.name),
f.value,
escape_json(&f.text),
escape_json(&f.caption),
f.enabled,
))
}
_ => Ok(r#"{"ok":false,"error":"not a form object"}"#.to_string()),
}
}
pub fn set_form_value_native(
&mut self,
sec: usize,
para: usize,
ci: usize,
value_json: &str,
) -> Result<String, crate::error::HwpError> {
let control = self
.document
.sections
.get_mut(sec)
.and_then(|s| s.paragraphs.get_mut(para))
.and_then(|p| p.controls.get_mut(ci));
match control {
Some(Control::Form(f)) => {
apply_form_value(f, value_json)?;
if let Some(s) = self.document.sections.get_mut(sec) {
s.raw_stream = None;
}
self.recompose_section(sec);
Ok(r#"{"ok":true}"#.to_string())
}
_ => Ok(r#"{"ok":false,"error":"not a form object"}"#.to_string()),
}
}
pub fn set_form_value_in_cell_native(
&mut self,
sec: usize,
table_para: usize,
table_ci: usize,
cell_idx: usize,
cell_para: usize,
form_ci: usize,
value_json: &str,
) -> Result<String, crate::error::HwpError> {
let form = self
.document
.sections
.get_mut(sec)
.and_then(|s| s.paragraphs.get_mut(table_para))
.and_then(|p| p.controls.get_mut(table_ci))
.and_then(|c| {
if let Control::Table(ref mut t) = c {
Some(t.as_mut())
} else {
None
}
})
.and_then(|t: &mut Table| t.cells.get_mut(cell_idx))
.and_then(|cell| cell.paragraphs.get_mut(cell_para))
.and_then(|p| p.controls.get_mut(form_ci))
.and_then(|c| {
if let Control::Form(ref mut f) = c {
Some(f)
} else {
None
}
});
match form {
Some(f) => {
apply_form_value(f, value_json)?;
if let Some(s) = self.document.sections.get_mut(sec) {
s.raw_stream = None;
}
self.recompose_section(sec);
Ok(r#"{"ok":true}"#.to_string())
}
None => Ok(r#"{"ok":false,"error":"cell form not found"}"#.to_string()),
}
}
pub fn get_form_object_info_native(
&self,
sec: usize,
para: usize,
ci: usize,
) -> Result<String, crate::error::HwpError> {
let control = self
.document
.sections
.get(sec)
.and_then(|s| s.paragraphs.get(para))
.and_then(|p| p.controls.get(ci));
match control {
Some(Control::Form(f)) => {
let form_type_str = form_type_to_str(f.form_type);
let props: Vec<String> = f
.properties
.iter()
.map(|(k, v)| format!(r#""{}":"{}""#, escape_json(k), escape_json(v)))
.collect();
let props_json = format!("{{{}}}", props.join(","));
let items_json = if f.form_type == FormType::ComboBox {
let items = f
.properties
.get("_rhwp_items")
.filter(|value| value.len() <= 65536)
.and_then(|value| serde_json::from_str::<Vec<String>>(value).ok())
.unwrap_or_else(|| {
extract_combobox_items_from_script(&self.document, &f.name)
});
if items.is_empty() {
"[]".to_string()
} else {
let arr: Vec<String> = items
.iter()
.map(|s| format!(r#""{}""#, escape_json(s)))
.collect();
format!("[{}]", arr.join(","))
}
} else {
"[]".to_string()
};
Ok(format!(
r#"{{"ok":true,"formType":"{}","name":"{}","value":{},"text":"{}","caption":"{}","enabled":{},"width":{},"height":{},"foreColor":{},"backColor":{},"properties":{},"items":{}}}"#,
form_type_str,
escape_json(&f.name),
f.value,
escape_json(&f.text),
escape_json(&f.caption),
f.enabled,
f.width,
f.height,
f.fore_color,
f.back_color,
props_json,
items_json,
))
}
_ => Ok(r#"{"ok":false,"error":"not a form object"}"#.to_string()),
}
}
}
fn apply_form_value(
f: &mut crate::model::control::FormObject,
value_json: &str,
) -> Result<(), crate::error::HwpError> {
let value: serde_json::Value = serde_json::from_str(value_json)
.map_err(|error| crate::error::HwpError::InvalidField(format!("양식 값 JSON: {error}")))?;
let fields = value.as_object().ok_or_else(|| {
crate::error::HwpError::InvalidField("양식 값은 JSON 객체여야 합니다".to_string())
})?;
if let Some(v) = fields
.get("value")
.and_then(serde_json::Value::as_i64)
.and_then(|v| i32::try_from(v).ok())
{
f.value = v;
}
if let Some(t) = fields.get("text").and_then(serde_json::Value::as_str) {
f.text = t.to_string();
}
if let Some(c) = fields.get("caption").and_then(serde_json::Value::as_str) {
f.caption = c.to_string();
}
Ok(())
}
fn find_form_node_at(
node: &RenderNode,
x: f64,
y: f64,
) -> Option<(&FormObjectNode, (f64, f64, f64, f64))> {
for child in &node.children {
if let Some(result) = find_form_node_at(child, x, y) {
return Some(result);
}
}
if let RenderNodeType::FormObject(ref form) = node.node_type {
let b = &node.bbox;
if x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height {
return Some((form, (b.x, b.y, b.width, b.height)));
}
}
None
}
fn form_type_to_str(ft: FormType) -> &'static str {
match ft {
FormType::PushButton => "PushButton",
FormType::CheckBox => "CheckBox",
FormType::ComboBox => "ComboBox",
FormType::RadioButton => "RadioButton",
FormType::Edit => "Edit",
}
}
fn decode_hwp_script(document: &crate::model::document::Document) -> Option<String> {
crate::model::form_script::script_sources_from_streams(document)
.ok()
.map(|(header, source)| format!("{header}\n{source}"))
}
fn extract_combobox_items_from_script(
document: &crate::model::document::Document,
control_name: &str,
) -> Vec<String> {
let script = match decode_hwp_script(document) {
Some(s) => s,
None => return Vec::new(),
};
let mut items: Vec<(usize, String)> = Vec::new();
let prefix = format!("{}.InsertString(", control_name);
for line in script.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix(&prefix) {
if let Some((text, idx)) = parse_insert_string_args(rest) {
items.push((idx, text));
}
}
}
items.sort_by_key(|(idx, _)| *idx);
items.into_iter().map(|(_, text)| text).collect()
}
fn parse_insert_string_args(args: &str) -> Option<(String, usize)> {
let rest = args.strip_prefix('"')?;
let end_quote = rest.find('"')?;
let text = rest[..end_quote].to_string();
let after_quote = &rest[end_quote + 1..];
let after_comma = after_quote.trim_start().strip_prefix(',')?;
let idx_str: String = after_comma
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let idx = idx_str.parse().unwrap_or(0);
Some((text, idx))
}
#[cfg(test)]
mod tests {
use crate::document_core::DocumentCore;
use crate::model::control::{Control, FormObject};
use crate::model::document::{Document, Section};
use crate::model::paragraph::Paragraph;
use crate::model::table::{Cell, Table};
use crate::serializer::body_text::serialize_section;
const SENTINEL: u8 = 0xAB;
fn core_from(doc: Document) -> DocumentCore {
let mut core = DocumentCore::new_empty();
core.document = doc;
core.composed = vec![Vec::new()];
core.dirty_sections = vec![true];
core.dirty_paragraphs = vec![None];
core
}
fn section_with_raw_stream(paragraphs: Vec<Paragraph>) -> Section {
Section {
paragraphs,
raw_stream: Some(vec![SENTINEL; 64]),
..Default::default()
}
}
fn body_form_doc() -> Document {
let mut para = Paragraph::default();
para.controls.push(Control::Form(Box::default()));
let mut doc = Document::default();
doc.sections.push(section_with_raw_stream(vec![para]));
doc
}
fn cell_form_doc() -> Document {
let mut cell_para = Paragraph::default();
cell_para.controls.push(Control::Form(Box::default()));
let mut table = Table::default();
table.row_count = 1;
table.col_count = 1;
table.cells = vec![Cell {
row: 0,
col: 0,
col_span: 1,
row_span: 1,
paragraphs: vec![cell_para],
..Default::default()
}];
let mut para = Paragraph::default();
para.controls.push(Control::Table(Box::new(table)));
let mut doc = Document::default();
doc.sections.push(section_with_raw_stream(vec![para]));
doc
}
#[test]
fn set_form_value_invalidates_section_raw_stream() {
let mut core = core_from(body_form_doc());
let r = core
.set_form_value_native(0, 0, 0, r#"{"value":1,"text":"동의함"}"#)
.expect("호출이 성공해야 함");
assert!(r.contains(r#""ok":true"#), "전제: 양식 값 설정 성공 ({r})");
match &core.document.sections[0].paragraphs[0].controls[0] {
Control::Form(f) => {
assert_eq!(f.value, 1);
assert_eq!(f.text, "동의함");
}
_ => panic!("양식 컨트롤이어야 함"),
}
assert!(
core.document.sections[0].raw_stream.is_none(),
"raw_stream 이 남으면 양식 값이 저장 시 통째로 사라진다"
);
let out = serialize_section(&core.document.sections[0]);
assert_ne!(
out,
vec![SENTINEL; 64],
"serialize_section 이 여전히 원본 바이트를 반환하면 값 유실"
);
}
#[test]
fn set_form_value_in_cell_invalidates_section_raw_stream() {
let mut core = core_from(cell_form_doc());
let r = core
.set_form_value_in_cell_native(0, 0, 0, 0, 0, 0, r#"{"value":1}"#)
.expect("호출이 성공해야 함");
assert!(
r.contains(r#""ok":true"#),
"전제: 셀 양식 값 설정 성공 ({r})"
);
assert!(
core.document.sections[0].raw_stream.is_none(),
"셀 안 양식 값도 섹션 raw_stream 을 비워야 저장에 반영된다"
);
}
}