rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! 양식 개체 조회/설정 API (Task 233)
//!
//! 렌더 트리에서 양식 개체를 좌표로 찾거나, 문서 트리에서 직접 값을 조회/설정한다.

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 {
    /// 페이지 좌표에서 양식 개체를 찾는다.
    ///
    /// 렌더 트리를 순회하며 FormObject 노드의 bbox와 좌표 충돌 검사.
    /// 반환: JSON 문자열
    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()
            };
            // sec/para는 최상위 문단 인덱스로 반환
            // cell_location이 있으면 table_para_index를 para로 사용
            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()),
        }
    }

    /// 양식 개체 값을 설정한다 (최상위 문단의 Form).
    ///
    /// value_json: `{"value":1}` 또는 `{"text":"입력값"}` 또는 둘 다
    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)?;
                // 원본 스트림 무효화 — serialize_section 은 raw_stream 이 있으면 원본
                // 바이트를 그대로 반환하므로(serializer/body_text.rs), 비우지 않으면
                // 방금 넣은 양식 값이 저장 시 통째로 사라진다. 화면은 recompose 로
                // 갱신되니 사용자는 저장이 됐다고 믿게 된다. 누름틀 쪽
                // set_field_value_*(field_query.rs)와 동일한 불변식이다.
                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()),
        }
    }

    /// 셀 내부 양식 개체 값을 설정한다.
    ///
    /// table_para: 표를 포함한 최상위 문단 인덱스
    /// table_ci: 표 컨트롤 인덱스
    /// cell_idx: 셀 인덱스
    /// cell_para: 셀 내 문단 인덱스
    /// form_ci: 셀 내 양식 컨트롤 인덱스
    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)?;
                // set_form_value_native 와 동일 — 셀 안 양식 값도 섹션 raw_stream 을
                // 비워야 저장 시 반영된다.
                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()),
        }
    }

    /// 양식 개체 상세 정보를 반환한다 (properties HashMap 포함).
    /// ComboBox인 경우 스크립트에서 추출한 항목 목록도 포함.
    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);
                // properties를 JSON 객체로 직렬화
                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(","));

                // ComboBox: 스크립트에서 InsertString 항목 추출
                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()),
        }
    }
}

/// form value/text/caption 적용 헬퍼
fn apply_form_value(
    f: &mut crate::model::control::FormObject,
    value_json: &str,
) -> Result<(), crate::error::HwpError> {
    // 전체 JSON을 먼저 읽어 잘못된 입력의 일부만 문서에 반영하지 않는다.
    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(())
}

/// 렌더 트리를 재귀 순회하여 좌표에 해당하는 FormObject 노드를 찾는다.
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",
    }
}

/// extra_streams에서 Scripts/DefaultJScript 스트림을 찾아 디코딩한다.
/// HWP 스크립트는 UTF-16LE로 저장되며 압축 여부는 문서의 저장 형태를 따른다(#8374).
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}"))
}

/// 스크립트에서 ComboBox InsertString 패턴을 추출하여 항목 목록을 반환한다.
///
/// 패턴: `컨트롤이름.InsertString("항목텍스트", 인덱스);`
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();

    // 패턴: ControlName.InsertString("text", index)
    // 또는: ControlName.InsertString("text",index)
    let prefix = format!("{}.InsertString(", control_name);
    for line in script.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix(&prefix) {
            // rest: `"봄",0);` 또는 `"봄", 0);`
            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()
}

/// InsertString 인자 파싱: `"텍스트", 인덱스);` → (텍스트, 인덱스)
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 {
    //! 양식 값 설정의 raw_stream 무효화 회귀 테스트.
    //!
    //! serialize_section(serializer/body_text.rs)은 raw_stream 이 Some 이면 IR 을 무시하고
    //! 원본 바이트를 그대로 반환한다. HWP5 파서는 모든 섹션에 raw_stream 을 채우므로
    //! (parser/mod.rs), 양식 값 설정이 raw_stream 을 비우지 않으면 — 양식 채우기만 하고
    //! 저장하는 표준 워크플로에서 — 입력한 값 전부가 저장 시 조용히 사라진다.
    //! 누름틀 쪽 set_field_value_*(field_query.rs)는 같은 불변식을 이미 지킨다.

    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})");

        // 값은 IR 에 반영됐고,
        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 이 남으면 양식 값이 저장 시 통째로 사라진다"
        );
        // 저장 경로 결과로도 확인: 원본 sentinel 바이트가 더 이상 그대로 나가지 않는다.
        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 을 비워야 저장에 반영된다"
        );
    }
}