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
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
//! 공통 개체 속성/헬퍼 + 새 번호 (object_ops 분할, #1904).

use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::paragraph::Paragraph;
use crate::model::shape::ShapeObject;

/// [#6740] 변환 파생 상태(`raw_rendering`)의 무효화 판정용 지문.
///
/// 직렬화기는 `raw_rendering` 이 비어 있을 때만 변환 행렬을 새로 만든다
/// (`serializer/control.rs` 의 rendering 블록). 그러므로 setter 가 값 변화 없이
/// raw 를 비우면 한컴 원본 행렬이 rhwp 재생성본으로 바뀌고, 속성 bag 에는 원본
/// 바이트가 없으므로 되돌릴 길이 없다(#5890 이중 장부 비용).
///
/// #6355 가 그림에서 도입한 판정과 같은 형태다 — 실제로 변환이 바뀐 뒤에만 비운다.
pub(crate) fn shape_transform_fingerprint(
    common: &crate::model::shape::CommonObjAttr,
    attr: &crate::model::shape::ShapeComponentAttr,
) -> (u32, u32, u32, u32, u32, u32, i16, bool, bool) {
    (
        common.width,
        common.height,
        common.horizontal_offset,
        common.vertical_offset,
        attr.current_width,
        attr.current_height,
        attr.rotation_angle,
        attr.horz_flip,
        attr.vert_flip,
    )
}

/// 다각형의 실제 편집 변환을 저장 행렬에 합성한다.
/// 위치만 옮기거나 같은 속성을 재적용할 때는 원본 행렬을 보존한다.
fn compose_affine(a: [f64; 6], b: [f64; 6]) -> [f64; 6] {
    [
        a[0] * b[0] + a[1] * b[3],
        a[0] * b[1] + a[1] * b[4],
        a[0] * b[2] + a[1] * b[5] + a[2],
        a[3] * b[0] + a[4] * b[3],
        a[3] * b[1] + a[4] * b[4],
        a[3] * b[2] + a[4] * b[5] + a[5],
    ]
}

pub(crate) fn update_changed_polygon_geometry(
    shape: &mut ShapeObject,
    before: (u32, u32, u32, u32, u32, u32, i16, bool, bool),
) {
    let after = shape_transform_fingerprint(shape.common(), shape.shape_attr());
    let geometry =
        |f: (u32, u32, u32, u32, u32, u32, i16, bool, bool)| (f.0, f.1, f.4, f.5, f.6, f.7, f.8);
    if geometry(before) == geometry(after) {
        return;
    }
    let current_frame =
        super::shape::group_geometry::frame_matrix(shape.common(), shape.shape_attr());
    let old_frame = super::shape::group_geometry::frame_matrix(
        &crate::model::shape::CommonObjAttr {
            width: before.0,
            height: before.1,
            ..Default::default()
        },
        &crate::model::shape::ShapeComponentAttr {
            original_width: shape.shape_attr().original_width,
            original_height: shape.shape_attr().original_height,
            current_width: before.4,
            current_height: before.5,
            rotation_angle: before.6,
            horz_flip: before.7,
            vert_flip: before.8,
            ..Default::default()
        },
    );
    let ShapeObject::Polygon(poly) = shape else {
        return;
    };
    let sa = &mut poly.drawing.shape_attr;
    let determinant = old_frame[0] * old_frame[4] - old_frame[1] * old_frame[3];
    if determinant == 0.0 || !determinant.is_finite() || poly.points.is_empty() {
        sa.raw_rendering.clear();
        return;
    }
    let inverse = [
        old_frame[4] / determinant,
        -old_frame[1] / determinant,
        (old_frame[1] * old_frame[5] - old_frame[4] * old_frame[2]) / determinant,
        -old_frame[3] / determinant,
        old_frame[0] / determinant,
        (old_frame[3] * old_frame[2] - old_frame[0] * old_frame[5]) / determinant,
    ];
    let source = if sa.has_saved_affine_geometry() {
        [
            sa.render_sx,
            sa.render_b,
            sa.render_tx,
            sa.render_c,
            sa.render_sy,
            sa.render_ty,
        ]
    } else {
        old_frame
    };
    // 원본 저장 행렬과 이상적인 배치 프레임 사이의 잔여 변환을 한 번 보존한다.
    // 매번 현재 frame에 합성하므로 회전 외곽 크기를 로컬 배율로 다시 쓰지 않고,
    // 여러 편집과 역연산도 직전 계산의 오차를 누적하지 않는다.
    let reference =
        poly.affine_edit_reference
            .get_or_insert(crate::model::shape::PolygonAffineEditReference {
                width: before.4,
                height: before.5,
                rotation: before.6,
                horz_flip: before.7,
                vert_flip: before.8,
                matrix: compose_affine(inverse, source),
            });
    let m = compose_affine(current_frame, reference.matrix);
    sa.render_sx = m[0];
    sa.render_b = m[1];
    sa.render_tx = m[2];
    sa.render_c = m[3];
    sa.render_sy = m[4];
    sa.render_ty = m[5];
    sa.raw_rendering = crate::serializer::control::serialize_affine_rendering(sa);
}

impl DocumentCore {
    /// 인라인 개체 편집 뒤 실제 줄과 후속 문단의 저장 흐름을 함께 갱신한다.
    pub(crate) fn reflow_body_inline_object_change(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        stored_end_before: Option<i32>,
    ) {
        self.reflow_paragraph(section_idx, para_idx);
        self.finish_body_inline_object_reflow(section_idx, para_idx, stored_end_before);
    }

    /// 이미 구성한 줄 결과를 후속 본문 원점에 반영한다. 같은 문단을 다시 조판하지 않는다.
    pub(crate) fn finish_body_inline_object_reflow(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        stored_end_before: Option<i32>,
    ) {
        let hwp3_layout = self.document.layout_profile().hwp3_layout();
        crate::renderer::composer::recalculate_section_vpos(
            &mut self.document.sections[section_idx].paragraphs,
            para_idx,
            None,
            stored_end_before,
            &self.styles,
            self.dpi,
            hwp3_layout,
        );
    }

    const COMMON_OBJ_ATTR_KNOWN_MASK: u32 = 0x01
        | (0x03 << 3)
        | (0x07 << 5)
        | (0x03 << 8)
        | (0x07 << 10)
        | (1 << 13)
        | (1 << 14)
        | (0x07 << 15)
        | (0x03 << 18)
        | (1 << 20)
        | (0x07 << 21)
        | (0x03 << 24)
        | (1 << 26)
        | (1 << 28);
    pub(crate) fn sync_common_obj_attr_known_bits(c: &mut crate::model::shape::CommonObjAttr) {
        // [#4400] pack_common_attr_bits 는 serializer 소유로 이동했다.
        let packed = crate::serializer::control::pack_common_attr_bits(c);
        c.attr = (c.attr & !Self::COMMON_OBJ_ATTR_KNOWN_MASK)
            | (packed & Self::COMMON_OBJ_ATTR_KNOWN_MASK);
    }
    pub(crate) fn is_structure_only_empty_paragraph(para: &Paragraph) -> bool {
        para.text.is_empty()
            && !para.controls.is_empty()
            && para
                .controls
                .iter()
                .all(|ctrl| matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)))
    }
    /// 본문 컨트롤 배열의 변경을 활성 누름틀의 같은 소유 주소에 반영한다.
    /// 셀 안의 필드는 맨 앞 경로가 본문 소유자이고, 나머지 경로와 필드 번호는 그대로다.
    pub(crate) fn remap_active_field_root_control(
        active_field: &mut Option<crate::document_core::ActiveFieldInfo>,
        section_idx: usize,
        para_idx: usize,
        remap: impl FnOnce(usize) -> Option<usize>,
    ) {
        let Some(active) = active_field.as_mut() else {
            return;
        };
        if active.section_idx != section_idx || active.para_idx != para_idx {
            return;
        }
        let owner = match active.cell_path.as_mut().and_then(|path| path.first_mut()) {
            Some((control_idx, _, _)) => control_idx,
            None => &mut active.control_idx,
        };
        if let Some(updated) = remap(*owner) {
            *owner = updated;
        } else {
            *active_field = None;
        }
    }

    /// 본문 컨트롤 삽입 뒤 같은 문단의 본문 또는 셀 활성 주소를 민다.
    pub(crate) fn shift_active_field_for_control_insert(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        control_idx: usize,
    ) {
        Self::remap_active_field_root_control(
            &mut self.active_field,
            section_idx,
            para_idx,
            |index| {
                Some(if index >= control_idx {
                    index + 1
                } else {
                    index
                })
            },
        );
    }
    /// 컨트롤 삭제 후 문단의 line_segs를 재계산한다.
    ///
    /// 그림/도형 삭제 시 문단의 line_segs에 컨트롤 높이가 그대로 남아,
    /// 레이아웃이 갱신되지 않는 문제를 방지한다.
    pub(crate) fn reflow_paragraph_line_segs_after_control_delete(
        para: &mut Paragraph,
        styles: &crate::renderer::style_resolver::ResolvedStyleSet,
        dpi: f64,
    ) {
        // [#4149] 컨트롤 삭제는 char_offsets −8 시프트로 compose 입력을 바꾼다 —
        // 높이만 조정하고 reflow_line_segs 를 타지 않는 분기(남은 컨트롤/빈 문단)도
        // 포함해 단일줄 과밀 memo 를 무효화한다. 삽입 쌍둥이
        // `shift_for_inline_control_insert` 와 대칭 (셀 그림/도형/수식/각주 삭제
        // 가족이 전부 이 함수로 수렴).
        para.invalidate_layout_inputs();
        // 남은 컨트롤 중 가장 큰 높이 계산
        let max_remaining_ctrl_height = para
            .controls
            .iter()
            .map(|ctrl| match ctrl {
                Control::Picture(pic) => pic.common.height as i32,
                Control::Shape(shape) => shape.common().height as i32,
                Control::Equation(eq) => eq.common.height as i32,
                _ => 0,
            })
            .max()
            .unwrap_or(0);

        if max_remaining_ctrl_height > 0 {
            // 아직 컨트롤이 남아있으면 가장 큰 컨트롤 높이로 설정
            if let Some(ls) = para.line_segs.first_mut() {
                ls.line_height = max_remaining_ctrl_height;
                ls.text_height = max_remaining_ctrl_height;
                ls.baseline_distance = (max_remaining_ctrl_height * 850) / 1000;
            }
        } else if para.text.is_empty() {
            // 글도 높이를 차지하는 컨트롤도 없음 → 기본 텍스트 높이의 한 줄로 다시 둔다.
            // 글 없는 문단의 줄 나눔은 0에서 시작하는 한 줄뿐이라 이 줄이 곧 새 줄 구성이다.
            // 위 무효화 표지만 남기면 저장기가 이 문단을 줄 없이 써서, 한/글이 쓰는 빈 문단
            // (PARA_TEXT 없이 줄 하나)과 달라진다.
            if let Some(mut ls) = para.line_segs.first().cloned() {
                ls.text_start = 0;
                ls.line_height = 1000;
                ls.text_height = 1000;
                ls.baseline_distance = 850;
                ls.line_spacing = 600;
                para.replace_line_segs(vec![ls]);
            }
        } else {
            // 텍스트가 있으면 reflow_line_segs로 재계산.
            //
            // 이 자리의 상자는 문단이 이미 들고 있던 상자다 — 컨트롤 하나를 지운
            // 것뿐이므로 원점도 폭도 종전 기록이 권위다. 스냅은 하지 않는다:
            // 저장값이 이미 한컴이 확정한 값이고, 여기서 다시 격자에 맞추면
            // 원본 기록을 우리 격자로 덮어쓴다.
            let stored = para.line_segs.first();
            let column_start = stored.map(|s| s.column_start).unwrap_or(0);
            let seg_width = stored.map(|s| s.segment_width).unwrap_or(0);
            crate::renderer::composer::reflow_line_segs(
                para,
                crate::renderer::composer::ParagraphBox::content(
                    column_start..column_start.saturating_add(seg_width),
                ),
                styles,
                dpi,
            );
        }
    }
    /// CommonObjAttr → JSON 문자열 (Shape/Picture 공용 속성)
    pub(crate) fn common_obj_attr_to_json(c: &crate::model::shape::CommonObjAttr) -> String {
        let vert_rel = match c.vert_rel_to {
            crate::model::shape::VertRelTo::Paper => "Paper",
            crate::model::shape::VertRelTo::Page => "Page",
            crate::model::shape::VertRelTo::Para => "Para",
        };
        let vert_align = match c.vert_align {
            crate::model::shape::VertAlign::Top => "Top",
            crate::model::shape::VertAlign::Center => "Center",
            crate::model::shape::VertAlign::Bottom => "Bottom",
            crate::model::shape::VertAlign::Inside => "Inside",
            crate::model::shape::VertAlign::Outside => "Outside",
        };
        let horz_rel = match c.horz_rel_to {
            crate::model::shape::HorzRelTo::Paper => "Paper",
            crate::model::shape::HorzRelTo::Page => "Page",
            crate::model::shape::HorzRelTo::Column => "Column",
            crate::model::shape::HorzRelTo::Para => "Para",
        };
        let horz_align = match c.horz_align {
            crate::model::shape::HorzAlign::Left => "Left",
            crate::model::shape::HorzAlign::Center => "Center",
            crate::model::shape::HorzAlign::Right => "Right",
            crate::model::shape::HorzAlign::Inside => "Inside",
            crate::model::shape::HorzAlign::Outside => "Outside",
        };
        let text_wrap = match c.text_wrap {
            crate::model::shape::TextWrap::Square => "Square",
            crate::model::shape::TextWrap::Tight => "Tight",
            crate::model::shape::TextWrap::Through => "Through",
            crate::model::shape::TextWrap::TopAndBottom => "TopAndBottom",
            crate::model::shape::TextWrap::BehindText => "BehindText",
            crate::model::shape::TextWrap::InFrontOfText => "InFrontOfText",
        };
        let desc_escaped = crate::document_core::helpers::json_escape(&c.description);
        format!(
            "\"width\":{},\"height\":{},\"treatAsChar\":{},\
             \"vertRelTo\":\"{}\",\"vertAlign\":\"{}\",\
             \"horzRelTo\":\"{}\",\"horzAlign\":\"{}\",\
             \"vertOffset\":{},\"horzOffset\":{},\
             \"textWrap\":\"{}\",\"restrictInPage\":{},\"allowOverlap\":{},\"sizeProtect\":{},\
             \"zOrder\":{},\"instanceId\":{},\
             \"outerMarginLeft\":{},\"outerMarginTop\":{},\
             \"outerMarginRight\":{},\"outerMarginBottom\":{},\
             \"description\":\"{}\",\"dropCapStyle\":\"{}\"",
            c.width,
            c.height,
            c.treat_as_char,
            vert_rel,
            vert_align,
            horz_rel,
            horz_align,
            c.vertical_offset,
            c.horizontal_offset,
            text_wrap,
            c.flow_with_text,
            c.allow_overlap,
            c.size_protect,
            c.z_order,
            c.instance_id,
            c.margin.left,
            c.margin.top,
            c.margin.right,
            c.margin.bottom,
            desc_escaped,
            crate::serializer::hwpx::shape::drop_cap_style_str(c.drop_cap_style),
        )
    }
    /// JSON → CommonObjAttr 필드 업데이트 (Shape/Picture 공용)
    pub(crate) fn apply_common_obj_attr_from_json(
        c: &mut crate::model::shape::CommonObjAttr,
        props_json: &str,
    ) {
        use crate::document_core::helpers::{json_bool, json_i16, json_str, json_u32};

        // [#6806] 퇴화값 0 만 최소 크기로 올린다. Undo 는 저장된 0 복원을 명시할 수 있다.
        let restore_stored_zero = json_bool(props_json, "restoreStoredZero") == Some(true);
        if let Some(w) = json_u32(props_json, "width") {
            c.width = super::clamp_degenerate_size(w, c.width, restore_stored_zero);
        }
        if let Some(h) = json_u32(props_json, "height") {
            c.height = super::clamp_degenerate_size(h, c.height, restore_stored_zero);
        }
        if let Some(tac) = json_bool(props_json, "treatAsChar") {
            c.treat_as_char = tac;
            if tac {
                c.attr |= 0x01;
            } else {
                c.attr &= !0x01;
            }
        }
        if let Some(v) = json_str(props_json, "vertRelTo") {
            c.vert_rel_to = match v.as_str() {
                "Paper" => crate::model::shape::VertRelTo::Paper,
                "Page" => crate::model::shape::VertRelTo::Page,
                "Para" => crate::model::shape::VertRelTo::Para,
                _ => c.vert_rel_to,
            };
        }
        if let Some(v) = json_str(props_json, "horzRelTo") {
            c.horz_rel_to = match v.as_str() {
                "Paper" => crate::model::shape::HorzRelTo::Paper,
                "Page" => crate::model::shape::HorzRelTo::Page,
                "Column" => crate::model::shape::HorzRelTo::Column,
                "Para" => crate::model::shape::HorzRelTo::Para,
                _ => c.horz_rel_to,
            };
        }
        if let Some(v) = json_str(props_json, "vertAlign") {
            c.vert_align = match v.as_str() {
                "Top" => crate::model::shape::VertAlign::Top,
                "Center" => crate::model::shape::VertAlign::Center,
                "Bottom" => crate::model::shape::VertAlign::Bottom,
                _ => c.vert_align,
            };
        }
        if let Some(v) = json_str(props_json, "horzAlign") {
            c.horz_align = match v.as_str() {
                "Left" => crate::model::shape::HorzAlign::Left,
                "Center" => crate::model::shape::HorzAlign::Center,
                "Right" => crate::model::shape::HorzAlign::Right,
                _ => c.horz_align,
            };
        }
        // 문단 첫 글자 장식 방식(한/글이 장식 글자를 담는 글상자에 둔다).
        if let Some(v) = json_str(props_json, "dropCapStyle") {
            c.drop_cap_style = match v.as_str() {
                "None" => crate::model::shape::DropCapStyle::None,
                "DoubleLine" => crate::model::shape::DropCapStyle::DoubleLine,
                "TripleLine" => crate::model::shape::DropCapStyle::TripleLine,
                "Margin" => crate::model::shape::DropCapStyle::Margin,
                _ => c.drop_cap_style,
            };
        }
        if let Some(v) = json_str(props_json, "textWrap") {
            c.text_wrap = match v.as_str() {
                "Square" => crate::model::shape::TextWrap::Square,
                "Tight" => crate::model::shape::TextWrap::Tight,
                "Through" => crate::model::shape::TextWrap::Through,
                "TopAndBottom" => crate::model::shape::TextWrap::TopAndBottom,
                "BehindText" => crate::model::shape::TextWrap::BehindText,
                "InFrontOfText" => crate::model::shape::TextWrap::InFrontOfText,
                _ => c.text_wrap,
            };
        }
        // [#6806] 「쪽 영역 안으로 제한」과 「서로 겹침 허용」은 독립이다 — 한컴은 둘을 동시에 켜서
        // 저장한다(corpus 그림 70·도형 12·표 39건). 종전의 "제한이면 겹침 해제" 결합은 파싱 경로에는
        // 없고 setter 에만 있어, 같은 봉지를 되먹이는 것만으로 겹침 허용이 꺼졌다.
        if let Some(v) = json_bool(props_json, "restrictInPage") {
            c.flow_with_text = v;
            if v {
                c.attr |= 1 << 13;
            } else {
                c.attr &= !(1 << 13);
            }
        }
        if let Some(v) = json_bool(props_json, "allowOverlap") {
            c.allow_overlap = v;
            if v {
                c.attr |= 1 << 14;
            } else {
                c.attr &= !(1 << 14);
            }
        }
        if let Some(v) = json_bool(props_json, "sizeProtect") {
            c.size_protect = v;
            if v {
                c.attr |= 1 << 20;
            } else {
                c.attr &= !(1 << 20);
            }
        }
        if let Some(v) = json_u32(props_json, "vertOffset") {
            c.vertical_offset = v;
        }
        if let Some(v) = json_u32(props_json, "horzOffset") {
            c.horizontal_offset = v;
        }
        if let Some(v) = json_str(props_json, "description") {
            c.description = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginLeft") {
            c.margin.left = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginTop") {
            c.margin.top = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginRight") {
            c.margin.right = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginBottom") {
            c.margin.bottom = v;
        }
        Self::sync_common_obj_attr_known_bits(c);
    }
    /// 직선 끝점 이동: 글로벌 좌표(HWPUNIT)로 시작/끝점을 직접 설정
    pub fn move_line_endpoint_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        control_idx: usize,
        start_x: i32,
        start_y: i32,
        end_x: i32,
        end_y: i32,
    ) -> Result<String, HwpError> {
        let section = self
            .document
            .sections
            .get_mut(section_idx)
            .ok_or_else(|| HwpError::RenderError("구역 범위 초과".to_string()))?;
        let para = section
            .paragraphs
            .get_mut(para_idx)
            .ok_or_else(|| HwpError::RenderError("문단 범위 초과".to_string()))?;
        let ctrl = para
            .controls
            .get_mut(control_idx)
            .ok_or_else(|| HwpError::RenderError("컨트롤 범위 초과".to_string()))?;
        let line = match ctrl {
            Control::Shape(ref mut s) => match s.as_mut() {
                ShapeObject::Line(ref mut l) => l,
                _ => return Err(HwpError::RenderError("직선이 아닙니다".to_string())),
            },
            _ => return Err(HwpError::RenderError("Shape이 아닙니다".to_string())),
        };

        let min_x = start_x.min(end_x);
        let min_y = start_y.min(end_y);
        let w = (start_x - end_x).abs().max(1);
        let h = (start_y - end_y).abs().max(0);

        line.common.horizontal_offset = min_x as u32;
        line.common.vertical_offset = min_y as u32;
        line.common.width = w as u32;
        line.common.height = h.max(1) as u32;
        line.start.x = start_x - min_x;
        line.start.y = start_y - min_y;
        line.end.x = end_x - min_x;
        line.end.y = end_y - min_y;

        line.drawing.shape_attr.current_width = w as u32;
        line.drawing.shape_attr.original_width = w as u32;
        line.drawing.shape_attr.current_height = h.max(1) as u32;
        line.drawing.shape_attr.original_height = h.max(1) as u32;
        line.drawing.shape_attr.rotation_center.x = w / 2;
        line.drawing.shape_attr.rotation_center.y = h / 2;
        line.drawing.shape_attr.raw_rendering = Vec::new();

        section.raw_stream = None;
        self.recompose_section(section_idx);
        self.paginate_if_needed();
        self.update_connectors_in_section(section_idx);

        Ok("{\"ok\":true}".to_string())
    }
    pub(crate) fn first_char_or_nul(value: &str) -> char {
        value.chars().next().unwrap_or('\0')
    }
    pub(crate) fn hwpunit16_from_json(json: &str, key: &str) -> Option<i16> {
        crate::document_core::helpers::json_i32(json, key)
            .map(|v| v.clamp(i16::MIN as i32, i16::MAX as i32) as i16)
    }
}

impl crate::document_core::DocumentCore {
    pub fn insert_new_number_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        start_num: u16,
    ) -> Result<String, crate::error::HwpError> {
        use crate::error::HwpError;
        use crate::model::control::{AutoNumberType, Control, NewNumber};

        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 new_number = NewNumber {
            number_type: AutoNumberType::Page,
            number: start_num,
        };

        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::NewNumber(new_number));
        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 << 0x0012;
        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();

        Ok(crate::document_core::helpers::json_ok_with(&format!(
            "\"controlIdx\":{}",
            insert_idx
        )))
    }
}