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
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! 유틸리티 함수 (BinData 검색, 번호 포맷, 도형 스타일 변환)

use super::super::page_layout::LayoutRect;
use super::super::render_tree::*;
use super::super::{format_number, ArrowStyle, LineStyle, NumberFormat as NumFmt, ShapeStyle};
use crate::model::bin_data::BinDataContent;
use crate::model::image::Picture;
use crate::model::style::{HeadType, Numbering, NUMBERING_LEVELS};

/// bin_data_id(1-indexed 순번)로 BinDataContent를 찾는다.
/// bin_data_id는 doc_info의 BinData 레코드 순번(1부터 시작)이며,
/// BinDataContent 배열도 같은 순서로 저장되어 있다.
///
/// HWPX 차트는 sparse id (60000+N) 를 사용하므로 인덱스 범위 밖일 때만 id 직접 검색.
/// 가드 `c.id == bin_data_id` 는 사용하지 않는다 — `c.id` 는 storage_id 이고 bin_data_id 는
/// 인덱스이므로, 두 값이 다른 경우 (예: hwpspec.hwp 1 페이지 표지) 정상 매칭이 거짓 실패함.
/// 자세한 정황: mydocs/troubleshootings/bin_data_id_index_mapping.md
pub(crate) fn find_bin_data<'a>(
    bin_data_content: &'a [BinDataContent],
    bin_data_id: u16,
) -> Option<&'a BinDataContent> {
    find_bin_data_index(bin_data_content, bin_data_id).map(|i| &bin_data_content[i])
}

/// [#4100] `find_bin_data` 와 **같은 규칙**으로 `bin_data_content` 안 인덱스를 돌려준다.
///
/// 차트 편집은 슬롯 바이트를 제자리에서 바꾸므로 참조가 아니라 인덱스가 필요하다.
/// 인덱스↔id 이중성 지식을 복제하지 않도록 `find_bin_data` 가 이 함수에 위임한다 —
/// 규칙이 갈리면 읽을 때와 쓸 때가 서로 다른 슬롯을 가리키게 된다.
pub(crate) fn find_bin_data_index(
    bin_data_content: &[BinDataContent],
    bin_data_id: u16,
) -> Option<usize> {
    crate::model::bin_data::content_index(bin_data_content, bin_data_id)
}

/// [#2550] `find_bin_data` + 압축 해제 상한 로드.
///
/// 상한 초과(deflate bomb 포함)는 `None` — 이미지 누락과 같은 placeholder 경로로
/// 접는다. 렌더 경로의 무제한 `load()` 는 이 함수로 대체한다.
pub(crate) fn find_bin_data_bytes(
    bin_data_content: &[BinDataContent],
    bin_data_id: u16,
) -> Option<Vec<u8>> {
    find_bin_data(bin_data_content, bin_data_id).and_then(|c| {
        c.data
            .load_limited(crate::model::bin_data::MAX_BIN_DATA_BYTES)
    })
}

/// 그림 자리에 **아무것도 그릴 수 없는** 상태인가 — "그림 미지정" 판정.
///
/// bin 참조 실패·빈 데이터뿐 아니라 **어느 백엔드도 디코드하지 못하는 바이트**도 같은
/// 상태로 본다(프리뷰 없는 텍스트 EPS/AI 등). 지금까지 후자는 소리 없이 빈 공간이 됐지만,
/// 한글은 둘을 구별하지 않고 편집 화면에 점선 테두리 + 그림-없음 아이콘을 그린다
/// (인쇄 등가 출력에서는 둘 다 미출력). 형식 판정의 단일 권위는 `image_resolver` 다.
pub(crate) fn picture_data_is_unusable(data: Option<&[u8]>) -> bool {
    match data {
        None => true,
        Some(bytes) => {
            bytes.is_empty() || !crate::renderer::image_resolver::is_displayable_image_data(bytes)
        }
    }
}

/// Picture의 렌더 표시 크기(HWPUNIT)를 반환한다.
///
/// 일부 HWP5 그림은 `CommonObjAttr.width/height`보다
/// `SHAPE_COMPONENT.current_width/current_height`가 실제 한컴 표시 크기에 가깝다.
/// 기존 도형 경로와 동일하게 current 값이 더 큰 축만 채택해 축소 회귀 위험을 줄인다.
///
/// [Issue #5595] 단, 회전 그림에서는 축별 max 를 쓰지 않는다. 회전 그림의
/// `common.width/height` 는 한컴이 저장한 **회전 후 외접 프레임**이고
/// `current_width/current_height` 는 **회전 전 원본 표시 크기**다 — 저장 경로의
/// `DocumentCore::refresh_picture_rotation_layout_for_save` 가 세우는 계약과 같다.
/// 90°/270° 처럼 두 축이 뒤바뀐 그림에 축별 max 를 적용하면 긴 변이 두 축 모두에
/// 들어가 **정사각형**이
/// 되어(00493: 188.5×134.0mm 가 712×712px) 지면 밖으로 나간다. 프레임 값이 온전하면
/// 회전 후 프레임(common)을 그대로 쓴다.
pub(crate) fn picture_display_size_hu(picture: &Picture) -> (i32, i32) {
    // 변환 행렬의 합성이 원래 그림을 저장된 개체 틀로 축소하는 경우 curSz는
    // 중간 단계의 크기다. 이를 최종 틀과 축별 max하면 그림이 다시 커진다.
    // 행렬과 HWPUNIT의 직렬화 반올림 차이만 허용하고, 서로 다른 크기를 나타내는
    // 손상된 common/current 사례는 기존 폴백을 유지한다.
    let attr = &picture.shape_attr;
    if picture.common.width > 0
        && picture.common.height > 0
        && attr.original_width > 0
        && attr.original_height > 0
        && !attr.raw_rendering.is_empty()
        && attr.render_b == 0.0
        && attr.render_c == 0.0
        && attr.rotation_angle.rem_euclid(360) == 0
    {
        let transformed_width = f64::from(attr.original_width) * attr.render_sx.abs();
        let transformed_height = f64::from(attr.original_height) * attr.render_sy.abs();
        if (transformed_width - f64::from(picture.common.width)).abs() <= 2.0
            && (transformed_height - f64::from(picture.common.height)).abs() <= 2.0
        {
            return (picture.common.width as i32, picture.common.height as i32);
        }
    }
    if picture.shape_attr.rotation_angle.rem_euclid(360) != 0
        && picture.common.width > 0
        && picture.common.height > 0
        && picture.shape_attr.current_width > 0
        && picture.shape_attr.current_height > 0
    {
        return (picture.common.width as i32, picture.common.height as i32);
    }

    let mut width = picture.common.width as i32;
    let mut height = picture.common.height as i32;

    let current_width = picture.shape_attr.current_width as i32;
    if current_width > 0 && current_width > width {
        width = current_width;
    }

    let current_height = picture.shape_attr.current_height as i32;
    if current_height > 0 && current_height > height {
        height = current_height;
    }

    (width, height)
}

/// [Issue #1230] 본문 float 그림의 배치/표시 프레임 크기.
///
/// 비-TAC + 텍스트가 옆으로 흐르는 wrap(Square/Tight/Through)에서는 파일
/// LINE_SEG(sw)/레이아웃이 `common`(개체 틀) 크기로 자리를 예약하므로, 표시도
/// 그 틀에 맞춰야 본문과 겹치지 않는다 (한컴 정합 — KICE EMF: common=198px 로
/// 그림, current=367px 는 과대). 저장 아핀 변환을 가진 비-TAC 그림도 변환 전
/// 크기를 개체 틀로 다시 사용하지 않고 공통 개체 크기를 소비한다. 그 외는 종전
/// `picture_display_size_hu`(max(common, current)) 유지 — #1122 문26(주머니
/// 그림: TAC, common.width 가 손상되어 current 가 정답) 회귀 방지.
/// 상대 크기 축의 common 값은 비율이므로 저장된 현재 HU 크기를 사용한다.
/// 이 물리 프레임을 배제 영역·저장 앵커 측정과 실제 그림 배치가 함께 소비한다.
pub(crate) fn picture_flow_frame_size_hu(picture: &Picture) -> (i32, i32) {
    let flows_beside = !picture.common.treat_as_char
        && matches!(
            picture.common.text_wrap,
            crate::model::shape::TextWrap::Square
                | crate::model::shape::TextWrap::Tight
                | crate::model::shape::TextWrap::Through
        );
    let saved_float_transform = !picture.common.treat_as_char
        && picture.shape_attr.group_level == 0
        && picture.shape_attr.has_saved_affine_geometry();
    if (flows_beside || saved_float_transform)
        && picture.common.width > 0
        && picture.common.height > 0
    {
        crate::renderer::stored_picture_metrics::stored_picture_size_hu(picture)
    } else {
        picture_display_size_hu(picture)
    }
}

/// [#7193] 그림 안쪽 여백을 개체 틀(`common`) 크기에 대한 비율로 돌려준다.
///
/// 한/글은 틀(`hp:sz`) 안에서 안쪽 여백(`hp:inMargin`)을 뺀 자리에 그림을 그린다 —
/// 틀은 `curSz + inMargin` 이다(코퍼스 HWPX 에서 여백 있는 그림 6/6 이 이 관계). 틀은
/// 흐름·선택의 기준이므로 바꾸지 않고, 비율로 넘겨 페인터가 실제 bbox 에 적용한다.
///
/// 적용하지 않는 경우(`None`): 여백이 모두 0, 틀 크기가 없음(묶음 자식 등), 회전 그림
/// (틀이 회전 후 외접 사각형이라 축이 맞지 않는다), 여백이 틀을 다 덮는 손상 값.
pub(crate) fn picture_content_inset(picture: &Picture) -> Option<[f64; 4]> {
    let p = &picture.padding;
    if p.left == 0 && p.right == 0 && p.top == 0 && p.bottom == 0 {
        return None;
    }
    let (w, h) = (picture.common.width as f64, picture.common.height as f64);
    if w <= 0.0 || h <= 0.0 || picture.shape_attr.rotation_angle.rem_euclid(360) != 0 {
        return None;
    }
    let inset = [
        f64::from(p.left.max(0)) / w,
        f64::from(p.top.max(0)) / h,
        f64::from(p.right.max(0)) / w,
        f64::from(p.bottom.max(0)) / h,
    ];
    (inset[0] + inset[2] < 1.0 && inset[1] + inset[3] < 1.0).then_some(inset)
}

/// 문단의 실효 numbering_id를 반환한다.
/// Outline 문단이고 para_style.numbering_id==0이면 구역의 outline_numbering_id로 fallback.
pub fn resolve_numbering_id(
    head_type: HeadType,
    para_numbering_id: u16,
    outline_numbering_id: u16,
) -> u16 {
    if para_numbering_id == 0 && head_type == HeadType::Outline {
        outline_numbering_id
    } else {
        para_numbering_id
    }
}

/// [#3307] 정의 없는 개요의 한컴 내장 기본 모양.
///
/// 개요 문단이 유효한 numbering 정의에 도달하지 못하면(문서에 `<hh:numbering>` 이
/// 없고 `outlineShapeIDRef=0`) 한컴 2020 은 **전 수준 레벨 경로 + 후행 마침표**로
/// 렌더한다 — level 0 `1.`, level 1 `2.1.`, … level 6 `2.5.1.1.1.2.1.`
/// (fixture 수준 스윕을 한컴 2020 MCP 로 실측, task #3307 Stage 1). 이는 기존
/// `^N` 제어코드와 동일하므로 형식 문자열만 합성한다. 기본 모양은 한컴이 파일에
/// 실체화하지 않는 편집기 내장 동작이라(재저장 실험으로 확인) 합성이 유일한 경로다.
///
/// [#8425] 머리 모양도 한컴 내장 값으로 합성한다. 한컴 2020(11.0.0.9136)·2024(13.0.0.3901)
/// Print 출력에서 12pt 개요 제목의 본문은 `번호 시작 + 수준별 참조 형식 폭 + 6.0pt`
/// (= 거리 50%)에서 시작한다. ^N의 예약 폭은 수준당 1em이며 실제 숫자·마침표의
/// 글리프 폭과 구분한다. 두 줄로 넘친 제목의 둘째 줄은 번호가 아니라 본문
/// 시작 위치에서 이어진다(자동 내어쓰기). 너비 보정은 0, 정렬은 왼쪽이다. 글자 모양은
/// 참조하지 않아(`u32::MAX`) 번호를 문단 글자 모양으로 재고 그린다 — 정의 없는 기본
/// 글머리표(`paragraph_layout` 의 `●` 합성)와 같은 머리 모양이다.
pub(crate) fn default_outline_numbering() -> Numbering {
    let mut n = Numbering::default();
    for f in n.level_formats.iter_mut() {
        *f = "^N".to_string();
    }
    for head in n.heads.iter_mut() {
        head.attr = DEFAULT_OUTLINE_HEAD_AUTO_INDENT;
        head.width_adjust = 0;
        head.text_distance = DEFAULT_OUTLINE_HEAD_TEXT_DISTANCE_PERCENT;
        head.char_shape_id = u32::MAX;
    }
    n.start_number = 1;
    n.level_start_numbers = [1; NUMBERING_LEVELS];
    n
}

/// 머리 모양 속성 bit 3: 자동 내어쓰기. bit 4(거리 단위) 0 은 글자 크기 대비 % 다.
const DEFAULT_OUTLINE_HEAD_AUTO_INDENT: u32 = 1 << 3;
/// 한컴 내장 기본 개요의 본문과의 거리 — 글자 크기의 50%.
const DEFAULT_OUTLINE_HEAD_TEXT_DISTANCE_PERCENT: i16 = 50;

/// 번호 형식 문자열의 `^` 제어코드를 실제 번호로 치환.
///
/// - `^1`~`^9`, `^:`: 해당 수준(1~10)의 번호. 한/글은 10수준을 `^:`(숫자 9 다음 글자)로 쓴다
/// - `^n`: 수준 1~현재 수준의 레벨 경로 (예: `1.1.1`)
/// - `^N`: 레벨 경로 + 후행 마침표 (예: `1.1.1.`)
///
/// `current_level`은 0-based 수준 인덱스(`para_level`).
pub(crate) fn expand_numbering_format(
    format_str: &str,
    counters: &[u32; NUMBERING_LEVELS],
    numbering: &Numbering,
    start_numbers: &[u32; NUMBERING_LEVELS],
    current_level: usize,
) -> String {
    let format_level = |idx: usize| -> String {
        let counter_val = counters[idx];
        let start = start_numbers[idx];
        let num = if counter_val > 0 {
            start.saturating_sub(1) + counter_val
        } else {
            start
        };
        let fmt_code = numbering.heads[idx].number_format;
        let num_fmt = NumFmt::from_hwp_format(fmt_code);
        format_number(num as u16, num_fmt)
    };

    let mut result = String::new();
    let mut chars = format_str.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '^' {
            match chars.peek() {
                Some(&digit @ '0'..=':') => {
                    chars.next();
                    let level_ref = (digit as u8 - b'0') as usize;
                    if (1..=NUMBERING_LEVELS).contains(&level_ref) {
                        result.push_str(&format_level(level_ref - 1));
                    }
                    continue;
                }
                Some(&code @ ('n' | 'N')) => {
                    chars.next();
                    for idx in 0..=current_level.min(NUMBERING_LEVELS - 1) {
                        if idx > 0 {
                            result.push('.');
                        }
                        result.push_str(&format_level(idx));
                    }
                    if code == 'N' {
                        result.push('.');
                    }
                    continue;
                }
                _ => {}
            }
        }
        result.push(ch);
    }
    result
}

/// 쪽 번호를 형식에 맞게 문자열로 변환 (mod.rs의 format_number 재사용)
pub(crate) fn format_page_number(
    page_num: u32,
    format: u8,
    prefix_char: char,
    suffix_char: char,
    dash_char: char,
    user_symbol: char,
) -> String {
    let formatted = crate::renderer::note_marker::number_text(page_num as u16, format, user_symbol);
    let prefix = if prefix_char != '\0' {
        prefix_char.to_string()
    } else {
        String::new()
    };
    let suffix = if suffix_char != '\0' {
        suffix_char.to_string()
    } else {
        String::new()
    };
    let dash = if dash_char != '\0' {
        dash_char.to_string()
    } else {
        String::new()
    };
    if prefix.is_empty() && suffix.is_empty() && dash.is_empty() {
        formatted
    } else if dash.is_empty() {
        format!("{}{}{}", prefix, formatted, suffix)
    } else {
        // [#3048] 대시 장식은 번호와 공백 한 칸을 두고 그린다 — 한글 오라클은
        // `- 1 -` (5자) 로 방출한다. 종전에는 `-1-` 로 붙여 폭이 좁았다.
        format!("{} {}{}{} {}", dash, prefix, formatted, suffix, dash)
    }
}

/// ShapeComponentAttr에서 ShapeTransform을 추출한다.
pub(crate) fn extract_shape_transform(
    sa: &crate::model::shape::ShapeComponentAttr,
) -> ShapeTransform {
    ShapeTransform {
        rotation: sa.rotation_angle as f64,
        horz_flip: sa.horz_flip,
        vert_flip: sa.vert_flip,
        image_frame_ratio: None,
    }
}

/// Common은 회전 후 점유 프레임, current는 회전 전 표시 크기다.
/// 기존 그림 레이아웃의 같은 source 계약을 paint에도 보존한다.
pub(crate) fn extract_picture_transform(picture: &Picture) -> ShapeTransform {
    let mut transform = extract_shape_transform(&picture.shape_attr);
    let shape = &picture.shape_attr;
    if shape.rotation_angle.rem_euclid(360) != 0
        && shape.current_width > 0
        && shape.current_height > 0
        && picture.common.width > 0
        && picture.common.height > 0
    {
        transform.image_frame_ratio = Some([
            f64::from(shape.current_width) / f64::from(picture.common.width),
            f64::from(shape.current_height) / f64::from(picture.common.height),
        ]);
    }
    transform
}

pub(crate) fn drawing_to_shape_style(
    drawing: &crate::model::shape::DrawingObjAttr,
    dpi: f64,
) -> (ShapeStyle, Option<Box<super::super::GradientFillInfo>>) {
    use super::super::GradientFillInfo;
    use crate::model::style::FillType;

    // 배경색: solid 필드가 있으면 fill_type과 무관하게 배경색 적용
    // (Image/Gradient와 단색 채우기가 동시에 적용되는 케이스 지원)
    let fill_color = drawing.fill.solid.and_then(|s| {
        // HWP pattern_type: >0이면 패턴 채우기(패턴이 배경색 처리), 0 이하=단색
        // ColorRef 상위 바이트가 0이 아니면(0xFF 등) 투명
        if s.pattern_type > 0 || (s.background_color >> 24) != 0 {
            None
        } else {
            Some(s.background_color)
        }
    });

    let gradient = match drawing.fill.fill_type {
        FillType::Gradient => drawing.fill.gradient.as_ref().map(|g| {
            let positions: Vec<f64> = if g.positions.is_empty() {
                let n = g.colors.len();
                (0..n)
                    .map(|i| i as f64 / (n.max(2) - 1).max(1) as f64)
                    .collect()
            } else {
                g.positions.iter().map(|&p| p as f64 / 100.0).collect()
            };
            // [#6822] `step`(띠 개수)·`step_center`(전이 위치)를 stop 으로 편다.
            let (colors, positions) =
                super::super::expand_gradient_steps(&g.colors, &positions, g.blur, g.step_center);
            Box::new(GradientFillInfo {
                gradient_type: g.gradient_type,
                angle: g.angle,
                center_x: g.center_x,
                center_y: g.center_y,
                colors,
                positions,
            })
        }),
        _ => None,
    };

    let border = &drawing.border_line;
    // 테두리 선 속성 비트 레이아웃 (hwplib LineInfoProperty 참조):
    //   bit 0-5:   선 종류 (LineType)
    //   bit 6-9:   선 끝 모양 (LineEndShape/cap)
    //   bit 10-15: 화살표 시작 모양
    //   bit 16-21: 화살표 끝 모양
    //   bit 22-25: 화살표 시작 크기
    //   bit 26-29: 화살표 끝 크기
    //   bit 30:    시작 화살표 채움
    //   bit 31:    끝 화살표 채움
    let shape_line_type = border.attr & 0x3F;
    let (mut stroke_width, mut stroke_color) = if shape_line_type == 0 {
        // 선 종류 "없음" → 테두리 그리지 않음
        (0.0, None)
    } else {
        let sw = crate::renderer::stroke_pattern::shape_pen_width_to_px(
            border.width,
            shape_line_type as u8,
        );
        let sc = if sw > 0.0 { Some(border.color) } else { None };
        (sw, sc)
    };

    // 선 종류가 지정되었으나 width가 0인 경우 기본 최소 선 굵기 적용
    // (한컴: line_type>0이면 width=0이어도 기본 얇은 선(0.12mm≈0.5px) 렌더링)
    if shape_line_type > 0 && stroke_width == 0.0 {
        stroke_width = 0.5; // 최소 0.5px (0.12mm 한컴 기본값)
        stroke_color = Some(border.color);
    }
    // 도형의 반복 구간은 선언 선 굵기에 비례하며, 임의 최소 픽셀 보강을 하지 않는다.
    let stroke_dash = crate::renderer::line_style::hwp_shape_line_type(shape_line_type as u8).0;

    // 채우기 투명도: 한컴 호환 — alpha=0은 불투명, alpha=255은 완전 투명
    let opacity = if drawing.fill.alpha > 0 {
        1.0 - (drawing.fill.alpha as f64 / 255.0)
    } else {
        1.0
    };
    // 패턴 채우기: pattern_type > 0일 때만 패턴 정보 생성 (1=가로줄, 2=세로줄, ..., 6=격자)
    let pattern = drawing.fill.solid.and_then(|s| {
        if s.pattern_type > 0 {
            Some(super::super::PatternFillInfo {
                pattern_type: s.pattern_type,
                tile_size: super::super::hwpunit_to_px(576, dpi),
                pattern_color: s.pattern_color,
                background_color: s.background_color,
            })
        } else {
            None
        }
    });

    // 그림자
    let shadow = if drawing.shadow_type > 0 {
        Some(super::super::ShadowStyle {
            shadow_type: drawing.shadow_type,
            color: drawing.shadow_color,
            offset_x: super::super::hwpunit_to_px(drawing.shadow_offset_x, 96.0),
            offset_y: super::super::hwpunit_to_px(drawing.shadow_offset_y, 96.0),
            alpha: drawing.shadow_alpha,
        })
    } else {
        None
    };

    let style = ShapeStyle {
        fill_color,
        pattern,
        stroke_color,
        stroke_width,
        stroke_dash,
        opacity,
        shadow,
    };
    (style, gradient)
}

/// DrawingObjAttr → LineStyle 변환 (직선용)
pub(crate) fn drawing_to_line_style(drawing: &crate::model::shape::DrawingObjAttr) -> LineStyle {
    let border = &drawing.border_line;
    let attr = border.attr;

    // 테두리 선 속성 비트 레이아웃 (hwplib LineInfoProperty 참조):
    //   bit 0-5:   선 종류 (LineType)
    //   bit 6-9:   선 끝 모양 (LineEndShape/cap)
    //   bit 10-15: 화살표 시작 모양 (LineArrowShape)
    //   bit 16-21: 화살표 끝 모양 (LineArrowShape)
    //   bit 22-25: 화살표 시작 크기 (LineArrowSize)
    //   bit 26-29: 화살표 끝 크기 (LineArrowSize)
    //   bit 30:    시작 화살표 채움
    //   bit 31:    끝 화살표 채움
    let shape_line_type = attr & 0x3F;
    let width =
        crate::renderer::stroke_pattern::shape_pen_width_to_px(border.width, shape_line_type as u8);

    let (dash, line_render_type) =
        crate::renderer::line_style::hwp_shape_line_type(shape_line_type as u8);

    // 화살표 시작 모양: bit 10-15
    let start_arrow_val = (attr >> 10) & 0x3F;
    let start_fill = (attr >> 30) & 1 != 0;
    let start_arrow = arrow_type_from_hwp(start_arrow_val, start_fill);

    // 화살표 끝 모양: bit 16-21
    let end_arrow_val = (attr >> 16) & 0x3F;
    let end_fill = (attr >> 31) & 1 != 0;
    let end_arrow = arrow_type_from_hwp(end_arrow_val, end_fill);

    // 화살표 크기: bit 22-25 (시작), bit 26-29 (끝)
    let start_arrow_size = ((attr >> 22) & 0x0F) as u8;
    let end_arrow_size = ((attr >> 26) & 0x0F) as u8;

    let shadow = if drawing.shadow_type > 0 {
        Some(super::super::ShadowStyle {
            shadow_type: drawing.shadow_type,
            color: drawing.shadow_color,
            offset_x: super::super::hwpunit_to_px(drawing.shadow_offset_x, 96.0),
            offset_y: super::super::hwpunit_to_px(drawing.shadow_offset_y, 96.0),
            alpha: drawing.shadow_alpha,
        })
    } else {
        None
    };

    LineStyle {
        color: border.color,
        width: if width > 0.0 { width } else { 0.5 },
        dash,
        dash_pattern: None,
        line_type: line_render_type,
        compound_component: false,
        preserve_fractional_position: false,
        start_arrow,
        end_arrow,
        start_arrow_size,
        end_arrow_size,
        shadow,
    }
}

/// HWP 화살표 모양 값 → ArrowStyle 변환
/// hwplib LineArrowShape 참조:
///   0=None, 1=Arrow, 2=LinedArrow, 3=ConcaveArrow,
///   4=Diamond, 5=Circle, 6=Rectangle
/// 채움 여부는 bit 30/31 (fill 파라미터)로 제어
fn arrow_type_from_hwp(hwp_type: u32, fill: bool) -> ArrowStyle {
    match hwp_type {
        0 => ArrowStyle::None,
        1 => ArrowStyle::Arrow,
        2 => ArrowStyle::OpenArrow, // SPEAR는 두 사선으로 된 열린 화살촉이다.
        3 => ArrowStyle::ConcaveArrow,
        4 => {
            if fill {
                ArrowStyle::Diamond
            } else {
                ArrowStyle::OpenDiamond
            }
        }
        5 => {
            if fill {
                ArrowStyle::Circle
            } else {
                ArrowStyle::OpenCircle
            }
        }
        6 => {
            if fill {
                ArrowStyle::Square
            } else {
                ArrowStyle::OpenSquare
            }
        }
        _ => ArrowStyle::None,
    }
}

/// LayoutRect → BoundingBox 변환
pub(crate) fn layout_rect_to_bbox(rect: &LayoutRect) -> BoundingBox {
    BoundingBox::new(rect.x, rect.y, rect.width, rect.height)
}

#[cfg(test)]
mod tests {
    use super::{find_bin_data, picture_display_size_hu};
    use crate::model::bin_data::BinDataContent;
    use crate::model::image::Picture;

    fn mk(id: u16, ext: &str) -> BinDataContent {
        BinDataContent {
            id,
            data: vec![].into(),
            extension: ext.to_string(),
        }
    }

    /// bin_data_id=0 은 항상 None
    #[test]
    fn find_bin_data_returns_none_for_zero() {
        let v = vec![mk(1, "png")];
        assert!(find_bin_data(&v, 0).is_none());
    }

    #[test]
    fn picture_display_size_uses_larger_current_axis() {
        let mut picture = Picture::default();
        picture.common.width = 3365;
        picture.common.height = 9446;
        picture.shape_attr.current_width = 9014;
        picture.shape_attr.current_height = 9446;

        assert_eq!(picture_display_size_hu(&picture), (9014, 9446));
    }

    #[test]
    fn picture_display_size_keeps_common_when_current_is_smaller() {
        let mut picture = Picture::default();
        picture.common.width = 9000;
        picture.common.height = 8000;
        picture.shape_attr.current_width = 3000;
        picture.shape_attr.current_height = 4000;

        assert_eq!(picture_display_size_hu(&picture), (9000, 8000));
    }

    /// [Issue #1230] 비-TAC Square wrap: current 가 부풀려져도 common 프레임 사용.
    #[test]
    fn picture_flow_frame_uses_common_for_square_wrap_float() {
        use super::picture_flow_frame_size_hu;
        let mut picture = Picture::default();
        picture.common.treat_as_char = false;
        picture.common.text_wrap = crate::model::shape::TextWrap::Square;
        picture.common.width = 14847; // KICE: 198px
        picture.common.height = 10230;
        picture.shape_attr.current_width = 27494; // 367px (과대)
        picture.shape_attr.current_height = 18956;

        assert_eq!(picture_flow_frame_size_hu(&picture), (14847, 10230));
        // 저장 행렬이 있는 떠 있는 그림도 변환 전 크기로 틀을 확대하지 않는다.
        let mut picture = Picture::default();
        picture.common.treat_as_char = false;
        picture.common.text_wrap = crate::model::shape::TextWrap::BehindText;
        picture.common.width = 6000;
        picture.common.height = 5000;
        picture.shape_attr.current_width = 12000;
        picture.shape_attr.current_height = 10000;
        picture.shape_attr.raw_rendering = vec![1];
        picture.shape_attr.render_sx = 0.5;
        picture.shape_attr.render_sy = 0.5;

        assert_eq!(picture_flow_frame_size_hu(&picture), (6000, 5000));
    }

    /// [Issue #1230/#1122] TAC 인라인은 종전 max 유지 (문26 주머니 그림 회귀 방지).
    #[test]
    fn picture_flow_frame_keeps_display_size_for_tac_inline() {
        use super::picture_flow_frame_size_hu;
        let mut picture = Picture::default();
        picture.common.treat_as_char = true;
        picture.common.text_wrap = crate::model::shape::TextWrap::Square;
        picture.common.width = 3365; // #1122 문26: 손상된 common
        picture.common.height = 9446;
        picture.shape_attr.current_width = 9014;
        picture.shape_attr.current_height = 9446;

        assert_eq!(picture_flow_frame_size_hu(&picture), (9014, 9446));
    }

    /// [Issue #1230] TopAndBottom float 은 종전 max 유지 (측면흐름 아님).
    #[test]
    fn picture_flow_frame_keeps_display_size_for_topbottom_float() {
        use super::picture_flow_frame_size_hu;
        let mut picture = Picture::default();
        picture.common.treat_as_char = false;
        picture.common.text_wrap = crate::model::shape::TextWrap::TopAndBottom;
        picture.common.width = 3365;
        picture.common.height = 9446;
        picture.shape_attr.current_width = 9014;
        picture.shape_attr.current_height = 9446;

        assert_eq!(picture_flow_frame_size_hu(&picture), (9014, 9446));
    }

    /// [Issue #1230] Square float 라도 common 이 0 이면 display size 로 폴백.
    #[test]
    fn picture_flow_frame_falls_back_when_common_is_zero() {
        use super::picture_flow_frame_size_hu;
        let mut picture = Picture::default();
        picture.common.treat_as_char = false;
        picture.common.text_wrap = crate::model::shape::TextWrap::Square;
        picture.common.width = 0;
        picture.common.height = 0;
        picture.shape_attr.current_width = 9014;
        picture.shape_attr.current_height = 9446;

        assert_eq!(picture_flow_frame_size_hu(&picture), (9014, 9446));
    }

    /// hwpspec.hwp 패턴 — bin_data_id=1 이 storage_id=12 를 가리킴 (가드 회귀 방지)
    #[test]
    fn find_bin_data_indexed_match_storage_id_differs() {
        let v = vec![
            mk(12, "png"), // index 0 → bin_data_id=1
            mk(1, "bmp"),  // index 1 → bin_data_id=2
            mk(2, "bmp"),  // index 2 → bin_data_id=3
        ];
        // bin_data_id=1 → 인덱스 0 의 BIN000C.png 매칭 (storage_id=12)
        let c = find_bin_data(&v, 1).expect("매칭 성공");
        assert_eq!(c.id, 12);
        assert_eq!(c.extension, "png");
    }

    /// 일반적인 케이스 — storage_id 가 인덱스와 일치
    #[test]
    fn find_bin_data_indexed_match_storage_id_matches() {
        let v = vec![mk(1, "jpg"), mk(2, "png"), mk(3, "bmp")];
        for i in 1..=3u16 {
            let c = find_bin_data(&v, i).expect("매칭 성공");
            assert_eq!(c.id, i);
        }
    }

    /// HWPX 차트 — sparse id 60000+N (인덱스 범위 밖)
    #[test]
    fn find_bin_data_sparse_id_for_hwpx_chart() {
        let v = vec![
            mk(1, "png"),
            mk(2, "png"),
            mk(60001, "ooxml_chart"),
            mk(60002, "ooxml_chart"),
        ];
        // bin_data_id=60001 → 인덱스 60000 범위 밖 → fallback id 직접 검색
        let c = find_bin_data(&v, 60001).expect("차트 매칭");
        assert_eq!(c.id, 60001);
        assert_eq!(c.extension, "ooxml_chart");

        let c2 = find_bin_data(&v, 60002).expect("차트 매칭");
        assert_eq!(c2.id, 60002);
    }

    /// 인덱스 범위 밖 + 일치 id 없음 → None
    #[test]
    fn find_bin_data_out_of_range_returns_none() {
        let v = vec![mk(1, "png"), mk(2, "png")];
        assert!(find_bin_data(&v, 99).is_none());
    }

    /// 차트 회귀 방지 — HWPX 의 실제 배열 구조 모사
    /// 일반 BinData (id=인덱스+1) 다음에 차트 (id=60000+N) 가 push 되는 형태
    #[test]
    fn find_bin_data_hwpx_realistic_layout_with_chart() {
        // HWPX 파서 (parser/hwpx/mod.rs:105-127) 의 실제 push 패턴 모사
        let v = vec![
            mk(1, "png"),             // index 0 — bin_data_id=1
            mk(2, "png"),             // index 1 — bin_data_id=2
            mk(3, "jpg"),             // index 2 — bin_data_id=3
            mk(60001, "ooxml_chart"), // index 3 — chart 1
            mk(60002, "ooxml_chart"), // index 4 — chart 2
        ];

        // 일반 그림: bin_data_id=1,2,3 → 인덱스 매칭
        for i in 1..=3u16 {
            let c = find_bin_data(&v, i).expect("그림 매칭");
            assert_eq!(c.id, i);
            assert!(c.extension == "png" || c.extension == "jpg");
        }

        // 차트: bin_data_id=60001,60002 → 인덱스 60000+ 범위 밖 → fallback id 검색
        let chart1 = find_bin_data(&v, 60001).expect("차트 1");
        assert_eq!(chart1.id, 60001);
        assert_eq!(chart1.extension, "ooxml_chart");

        let chart2 = find_bin_data(&v, 60002).expect("차트 2");
        assert_eq!(chart2.id, 60002);

        // 차트의 인덱스 위치 (3, 4) 는 일반 그림처럼 1-indexed 로도 접근 가능하지만
        // 차트는 bin_data_id=60001/60002 로 호출되므로 영향 없음
    }

    /// HWP 패턴 — storage_id sparse 한 일반 그림 (hwpspec.hwp 1 페이지 페이지 표지)
    #[test]
    fn find_bin_data_hwp_hwpspec_page_bg_pattern() {
        // hwpspec.hwp 의 실제 BinData 매핑 (앞부분 14개)
        // 트러블슈팅 문서의 표 참고
        let v = vec![
            mk(0x000C, "png"), // index 0 — bin_data_id=1 → 페이지 표지 (BIN000C.png, 1137 bytes)
            mk(0x0001, "bmp"), // index 1 — bin_data_id=2
            mk(0x0002, "bmp"), // index 2 — bin_data_id=3
            mk(0x0003, "bmp"), // index 3
            mk(0x0004, "bmp"), // index 4
            mk(0x0005, "bmp"), // index 5
            mk(0x0006, "bmp"), // index 6
            mk(0x0007, "bmp"), // index 7
            mk(0x0008, "bmp"), // index 8
            mk(0x0009, "bmp"), // index 9
            mk(0x000A, "bmp"), // index 10
            mk(0x000B, "bmp"), // index 11
            mk(0x002B, "png"), // index 12 — bin_data_id=13
            mk(0x000D, "bmp"), // index 13 — bin_data_id=14
        ];

        // 페이지 표지 — bin_data_id=1 → 인덱스 0 → storage_id=12 (PNG)
        let bg = find_bin_data(&v, 1).expect("페이지 표지");
        assert_eq!(
            bg.id, 0x000C,
            "회귀: bin_data_id=1 이 storage_id=12 가 아님 (가드가 정상 매칭을 거짓 실패시킴)"
        );
        assert_eq!(bg.extension, "png");

        // bin_data_id=14 → 인덱스 13 → storage_id=13 (BMP)
        let p2 = find_bin_data(&v, 14).expect("두 번째 표지");
        assert_eq!(p2.id, 0x000D);
        assert_eq!(p2.extension, "bmp");
    }
}