rhwp 0.9.1

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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! 수식 native 명령 (object_ops 분할, #1904).

use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;

/// [#7105] 수식 편집 명령이 대상이 수식이 아닐 때 낼 오류.
///
/// 한/글 5.x·97 계열이 `hwpeq5X.ocx` 로 저장한 수식은 native `$eqed` 컨트롤이 아니라
/// **OLE 개체**(`Control::Shape(ShapeObject::Ole)`)다. rhwp 는 그 `Contents` 스트림의
/// 스크립트를 읽어 렌더하지만(`shape_layout.rs` 의 `parse_equation_contents_script`),
/// 되쓰는 경로가 없다 — `raw_contents` 는 읽기 전용이고, 편집분을 현행 문법으로 써 넣으면
/// 한/글이 그 개체를 못 읽는다(한/글은 레거시 `\CMD … \TAB` 방언을 기대한다).
///
/// 직접 수식 API는 이 경우에도 먼저 변환 명령을 거쳐야 하므로, "수식이 아니다"가 아니라
/// **전환이 필요한 이유**를 말한다. UI의 `promote_ole_equation_native` 는 스크립트를 native
/// equation으로 안전하게 옮긴 뒤 이 API를 호출한다. 개체 자체의 삭제·이동은 도형 경로
/// (`delete-control` · `delete-shape`)로도 된다.
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 {
    /// 레거시 `hwpeq5X` OLE 수식을 native equation으로 승격한다.
    ///
    /// 레거시 OLE의 `Contents`는 한/글 5.x 방언을 담고 있어, 편집 결과를 그 바이트에
    /// 다시 쓰면 한/글 호환성이 깨진다. 대신 파싱된 스크립트를 현행 문법으로 정규화한
    /// native `$eqed` 컨트롤로 **같은 문단·컨트롤 슬롯**에서 교체한다. 따라서 인라인
    /// 문자 위치와 뒤 컨트롤의 인덱스는 변하지 않으며, 이후에는 일반 수식 편집·저장
    /// 경로를 사용한다.
    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);

        // OLE 렌더러도 수식 높이를 OLE 상자에 맞춰 정하므로, 초기 편집 글자 크기도 같은
        // 높이 비로 추정한다. 상자 자체는 그대로 보존해 전환 직후 위치·크기가 움직이지 않는다.
        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};

        // [#6807] 자동 크기 재계산의 근거는 "크기 키가 없다" 가 아니라 "크기를 결정하는 값이
        // 바뀌었다" 다. 종전에는 색·기준선·글꼴 이름만 담은 봉지에도 `intrinsic_size_hwp` 가
        // 돌아 한컴이 저장한 상자 크기를 rhwp 계산값으로 바꿨다(corpus 수식 2257건 전부 해당).
        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);

        // [#5890] 파생(자동 크기)은 봉지가 크기를 지정하지 않은 축에만 적용한다.
        // 종전에는 무조건 덧써서 getter 가 낸 봉지를 그대로 먹여도 크기가 바뀌었다
        // (get∘set ≠ 항등) — 속성 봉지만으로 되돌릴 수 없는 조작이 되고,
        // apply_common_obj_attr_from_json 이 방금 반영한 width/height 도 조용히 무시됐다.
        // UI 다이얼로그는 변경된 키만 담은 부분 봉지를 보내므로(width/height 미포함)
        // 스크립트·글자크기 편집의 자동 크기 재계산은 종전대로 동작한다.
        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;
            }
        }

        // [#5890] raw 패스스루 무효화는 파괴가 아니라 판정으로 한다.
        // serialize_equation_control 은 raw_ctrl_data 가 비어있지 않으면 원본 CTRL_HEADER
        // 바이트를 방출하지만, #4495 봉인이 서 있으면 `common` 변경만으로 봉인이 어긋나
        // 저장기가 IR 합성으로 내려간다 — 원본 바이트를 지우지 않아도 편집(크기/위치/
        // treat_as_char)은 .hwp 저장에 반영된다. 지우지 않으면 `common` 을 되돌렸을 때
        // 봉인이 다시 맞아 원본 바이트가 그대로 살아난다(속성 봉지만으로 되돌리는 참 역연산).
        // 봉인이 없는 raw(파서를 거치지 않은 합성 IR·어댑터 산출)는 판정 근거가 없어
        // 종전대로 비운다(table_ops 셀 편집 가드, adapt_equation 의 hwpx→hwp 변환과 동형).
        // EQEDIT 자식 레코드(script/font)는 어느 쪽이든 IR 로 재생성되므로 무관.
        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;

        // 편집한 슬롯·기준선은 공통 줄 구성에서도 소비해야 한다. paint만
        // 재조판하면 저장 LineSeg의 옛 기준선·점유 높이가 그대로 남는다.
        // 색상·getter 봉지 같은 비기하 편집은 기존 저장 프레임을 유지한다.
        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,
                );
            }
        }

        // 셀 수식은 최외곽 문단의 측정 revision을 무효화한다.
        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())
    }
    /// 수식 스크립트를 SVG로 렌더링하여 반환한다 (미리보기 전용).
    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)
    }
    /// 수식(Equation) 컨트롤을 문단에서 삭제한다.
    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!(&para.controls[control_idx], Control::Equation(_)) {
            return Err(not_an_equation_error(&para.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())
    }

    // ─── 각주 삽입/삭제 API ──────────────────────────────
    /// 본문 문단에 수식을 삽입한다 (표 셀/글상자 내부는 미지원).
    /// 커서 위치에 수식 컨트롤을 추가한다.
    /// 반환: JSON `{"ok":true, "paraIdx":N, "controlIdx":N}`
    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();
        // 한컴 계열 0x44 접두는 유지하되, 접두와 겹치지 않는 하위 26비트에 문서 전체
        // 수식 순서를 배정한다. 구역 번호를 OR하면 구역 0과 64가 같은 ID가 된다.
        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,
                // 한컴 저장본의 인라인 수식 계약: 문단 기준 위치, 절대 크기,
                // 글자처럼 취급, 글과 함께 이동, 위아래 배치, 수식 번호 범주(bit 26-27 = 3).
                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
        };

        // [#3214] controls 기준 인덱스를 ctrl_data_records 에 그대로 쓰기 전에 정렬한다.
        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);

        // 본문 문단 리플로우
        // 본문 문단의 상자는 쪽 폭이 아니라 **열** 폭에서 나온다. 직접 계산하면
        // ColumnDef(다단)·margin_gutter·가로 용지·양면 짝수쪽 여백 교환·손상
        // PageDef 의 A4 폴백을 모두 놓친다 — 그리고 그 결과가 디스크로 나간다.
        // 대화형 편집의 관문과 같은 한 곳을 쓴다.
        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;

    /// 봉인이 없는 raw(파서를 거치지 않은 합성 IR·어댑터 산출)는 저장기가 원본
    /// CTRL_HEADER 를 무조건 방출하므로, 판정 근거가 없어 종전대로 비워야 한다.
    /// 비우지 않으면 크기/위치 편집이 저장에서 원복된다.
    #[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 저장에 반영된다"
        );
    }
}