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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! 수식 SVG 렌더러
//!
//! LayoutBox를 SVG 요소로 변환한다.
//! 생성된 SVG 조각은 `<g>` 요소 내부에 포함된다.

use super::ast::MatrixStyle;
use super::layout::*;
use super::symbols::{DecoKind, FontStyleKind};

/// 수식 전용 font-family
/// 순서: Latin Modern Math (LaTeX 설치 시) → STIX Two Text (Mac/STIX 설치 시) → STIX Two Math → Times New Roman (Windows 기본) → serif
/// Cambria Math 는 Windows 에서 "볼드 인상" 을 유발해 제외. Pretendard 는 산세리프라 수식 부적합으로 제외. (Task #280)
pub const DEFAULT_EQUATION_FONT_FAMILY_ATTR: &str =
    "font-family=\"'Latin Modern Math', 'STIX Two Text', 'STIX Two Math', 'Times New Roman', 'Times', serif\"";
const EQ_FONT_FAMILY: &str = " font-family=\"'Latin Modern Math', 'STIX Two Text', 'STIX Two Math', 'Times New Roman', 'Times', serif\"";

/// 수식을 SVG 조각 문자열로 렌더링
///
/// 진입점 default: italic=true (hwpeq 변수 기본 스타일). FontStyle::Roman(`rm`)
/// 적용 영역에서는 자식 렌더링 시 italic=false 로 전환된다.
pub fn render_equation_svg(layout: &LayoutBox, color: &str, base_font_size: f64) -> String {
    let mut svg = String::new();
    render_box(
        &mut svg,
        layout,
        0.0,
        0.0,
        color,
        base_font_size,
        true,
        false,
    );
    svg
}

fn render_box(
    svg: &mut String,
    lb: &LayoutBox,
    parent_x: f64,
    parent_y: f64,
    color: &str,
    fs: f64,
    italic: bool,
    bold: bool,
) {
    let fs = if lb.font_size > 0.0 { lb.font_size } else { fs };
    let x = parent_x + lb.x;
    let y = parent_y + lb.y;

    match &lb.kind {
        LayoutKind::HancomGlyphs(run) => {
            for ((glyph, offset), shear) in run.glyphs.chars().zip(&run.positions).zip(&run.shears)
            {
                svg.push_str(&format!(
                    "<text x=\"0\" y=\"0\" transform=\"matrix(1 0 {} 1 {:.2} {:.2})\" font-size=\"{:.2}\" fill=\"{}\" font-family=\"{}\">{}</text>\n",
                    -shear, x + offset, y + lb.baseline + run.baseline_shift, fs, color,
                    run.font_family, escape_xml(&glyph.to_string()),
                ));
            }
        }
        LayoutKind::Row(children) => {
            for child in children {
                render_box(svg, child, x, y, color, fs, italic, bold);
            }
        }
        LayoutKind::Text(text) => {
            let text_x = x;
            let text_y = y + lb.baseline;
            let esc = escape_xml(text);
            let fi = fs;
            // CJK/한글 텍스트는 이탤릭 없이 렌더링 (수학 변수명만 이탤릭).
            // FontStyle::Roman(`rm` 적용)으로 italic=false 가 전달된 경우에도 이탤릭을 적용하지 않는다.
            let has_cjk = super::text_has_cjk(text);
            let styled = is_styled_variable(text);
            let italic_attr = if !has_cjk && italic && !styled {
                " font-style=\"italic\""
            } else {
                ""
            };
            let weight_attr = if bold && !styled {
                " font-weight=\"bold\""
            } else {
                ""
            };
            if has_cjk && (lb.width - estimate_text_width(text, fi, false)).abs() > 0.01 {
                for (ch, offset) in super::positioned_cjk_text(text, fi, lb.width) {
                    svg.push_str(&format!(
                        "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{} font-family=\"'Haansoft Batang', '한컴바탕', 'Batang', '바탕', serif\">{}</text>\n",
                        text_x + offset, text_y, fi, color, weight_attr, escape_xml(&ch.to_string()),
                    ));
                }
                return;
            }
            svg.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}{}{}>{}</text>\n",
                text_x,
                text_y,
                fi,
                color,
                italic_attr,
                weight_attr,
                if has_cjk {
                    " font-family=\"'Haansoft Batang', '한컴바탕', 'Batang', '바탕', serif\""
                } else {
                    EQ_FONT_FAMILY
                },
                esc,
            ));
        }
        LayoutKind::Number(text) => {
            let text_x = x;
            let text_y = y + lb.baseline;
            let esc = escape_xml(text);
            let fi = fs;
            let style_attr = if bold { " font-weight=\"bold\"" } else { "" };
            svg.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}{}>{}</text>\n",
                text_x, text_y, fi, color, style_attr, EQ_FONT_FAMILY, esc,
            ));
        }
        LayoutKind::Symbol(text) => {
            let text_x = x + lb.width / 2.0;
            let text_y = y + lb.baseline;
            let esc = escape_xml(text);
            let fi = fs;
            svg.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\" text-anchor=\"middle\"{}>{}</text>\n",
                text_x, text_y, fi, color, EQ_FONT_FAMILY, esc,
            ));
        }
        LayoutKind::FontGlyph {
            text,
            font_family,
            outline,
            paint,
        } => {
            if let Some(commands) = outline {
                let scale_x = paint.map_or(1.0, |p| p.scale_x);
                let stroke = paint.map_or_else(String::new, |p| format!(
                    " stroke=\"{color}\" stroke-width=\"{:.6}\" stroke-linejoin=\"miter\" stroke-miterlimit=\"10\"",
                    p.stroke_width,
                ));
                svg.push_str(&format!(
                    "<path d=\"{}\" transform=\"translate({x:.4},{y:.4}) scale({scale_x:.8},1)\" fill=\"{color}\"{stroke}/>\n",
                    super::multiplication_outline::path_data(commands),
                ));
                return;
            }
            let scale_x = paint.map_or(1.0, |p| p.scale_x);
            if scale_x != 1.0 {
                svg.push_str(&format!(
                    "<text x=\"0\" y=\"0\" transform=\"translate({:.4},{:.4}) scale({scale_x:.8},1)\" font-size=\"{fs:.4}\" fill=\"{color}\" font-family=\"{}\">{}</text>\n",
                    x, y + lb.baseline, escape_xml(font_family), escape_xml(text),
                ));
            } else {
                svg.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\" font-family=\"{}\">{}</text>\n",
                x, y + lb.baseline, fs, color, escape_xml(font_family), escape_xml(text),
            ));
            }
        }
        LayoutKind::MathSymbol(text) => {
            // 적분 기호(∫): 공통 공개 글리프 윤곽을 사용한다.
            // 폰트 미임베딩 SVG 에서 뷰어 대체 폰트의 글리프 bbox 편차로 상·하한이
            // 어긋나던 문제를, 폰트 독립·결정적 path 로 해소한다(geom SSOT).
            if super::layout::is_integral_symbol(text) {
                svg.push_str(&integral_path(x, y, fs, color));
            } else {
                let text_x = x;
                let text_y = y + lb.baseline;
                let esc = escape_xml(text);
                svg.push_str(&format!(
                    "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
                    text_x, text_y, fs, color, EQ_FONT_FAMILY, esc,
                ));
            }
        }
        LayoutKind::Function(name) => {
            let text_x = x;
            let text_y = y + lb.baseline;
            let esc = escape_xml(name);
            let fi = fs;
            svg.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
                text_x, text_y, fi, color, EQ_FONT_FAMILY, esc,
            ));
        }
        LayoutKind::Fraction {
            numer,
            denom,
            axis_height,
            rule_thickness,
            rule_start,
            rule_end,
        } => {
            // 분자
            render_box(svg, numer, x, y, color, fs, italic, bold);
            // 분수선 — baseline에서 axis_height 위에 배치
            let line_y = y + lb.baseline - axis_height;
            let line_thick = rule_thickness;
            svg.push_str(&format!(
                "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                x + rule_start, line_y,
                x + rule_end, line_y,
                color, line_thick,
            ));
            // 분모
            render_box(svg, denom, x, y, color, fs, italic, bold);
        }
        LayoutKind::Atop { top, bottom } => {
            render_box(svg, top, x, y, color, fs, italic, bold);
            render_box(svg, bottom, x, y, color, fs, italic, bold);
        }
        LayoutKind::Sqrt { index, body } => {
            let geometry = super::radical_outline::geometry(lb, body, fs);
            svg.push_str(&format!(
                "<path d=\"{}\" transform=\"translate({x:.4},{y:.4})\" fill=\"{color}\"/>\n",
                super::multiplication_outline::path_data(&geometry.outline),
            ));
            svg.push_str(&format!(
                "<line x1=\"{:.4}\" y1=\"{:.4}\" x2=\"{:.4}\" y2=\"{:.4}\" stroke=\"{color}\" stroke-width=\"{:.4}\"/>\n",
                x + geometry.bar_start.0, y + geometry.bar_start.1,
                x + geometry.bar_end.0, y + geometry.bar_end.1,
                geometry.rule_thickness,
            ));

            // 인덱스 (있으면)
            if let Some(idx) = index {
                render_box(
                    svg,
                    idx,
                    x,
                    y,
                    color,
                    fs * super::layout::RADICAL_DEGREE_SCALE,
                    false,
                    false,
                );
            }

            // 본체
            render_box(svg, body, x, y, color, fs, italic, bold);
        }
        LayoutKind::Superscript { base, sup } => {
            render_box(svg, base, x, y, color, fs, italic, bold);
            render_box(
                svg,
                sup,
                x,
                y,
                color,
                fs * super::layout::SCRIPT_SCALE,
                italic,
                bold,
            );
        }
        LayoutKind::Subscript { base, sub } => {
            render_box(svg, base, x, y, color, fs, italic, bold);
            render_box(
                svg,
                sub,
                x,
                y,
                color,
                fs * super::layout::SCRIPT_SCALE,
                italic,
                bold,
            );
        }
        LayoutKind::SubSup { base, sub, sup } => {
            render_box(svg, base, x, y, color, fs, italic, bold);
            render_box(
                svg,
                sub,
                x,
                y,
                color,
                fs * super::layout::SCRIPT_SCALE,
                italic,
                bold,
            );
            render_box(
                svg,
                sup,
                x,
                y,
                color,
                fs * super::layout::SCRIPT_SCALE,
                italic,
                bold,
            );
        }
        LayoutKind::BigOp {
            symbol,
            sub,
            sup,
            op_font_size,
            op_x,
            op_y,
            op_baseline,
            ..
        } => {
            let is_integral = super::layout::is_integral_symbol(symbol);
            // 생산 단계에서 확정한 표시 글자 크기와 원점을 소비한다.
            let op_fs = *op_font_size;
            let esc = escape_xml(symbol);

            if is_integral {
                // 적분: 기호는 왼쪽, 첨자는 오른쪽 위/아래 (nolimits).
                // Task #1317: 폰트 `<text>` 대신 stroke path 로 렌더(geom SSOT).
                svg.push_str(&integral_path(x + op_x, y + op_y, fs, color));
            } else {
                // ∑, ∏ 등: 기호는 중앙, 첨자는 위/아래 (limits)
                let op_x = x + op_x;
                let op_y = y + op_baseline;
                svg.push_str(&format!(
                    "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
                    op_x, op_y, op_fs, color, EQ_FONT_FAMILY, esc,
                ));
            }
            // 위/아래 첨자: LayoutBox의 자식 좌표로 배치
            if let Some(sup_box) = sup {
                render_box(
                    svg,
                    sup_box,
                    x,
                    y,
                    color,
                    fs * super::layout::SCRIPT_SCALE,
                    false,
                    false,
                );
            }
            if let Some(sub_box) = sub {
                render_box(
                    svg,
                    sub_box,
                    x,
                    y,
                    color,
                    fs * super::layout::SCRIPT_SCALE,
                    false,
                    false,
                );
            }
        }
        LayoutKind::Limit {
            is_upper,
            name,
            name_font_size,
            sub_font_size,
            sub,
        } => {
            if let Some(name) = name {
                render_box(svg, name, x, y, color, name.height, false, false);
            } else {
                let name = if *is_upper { "Lim" } else { "lim" };
                svg.push_str(&format!(
                    "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
                    x,
                    y + lb.baseline,
                    name_font_size,
                    color,
                    EQ_FONT_FAMILY,
                    name,
                ));
            }
            if let Some(sub_box) = sub {
                render_box(svg, sub_box, x, y, color, *sub_font_size, false, false);
            }
        }
        LayoutKind::Matrix { cells, style } => {
            // 괄호
            let bracket_chars = match style {
                MatrixStyle::Paren => ("(", ")"),
                MatrixStyle::Bracket => ("[", "]"),
                MatrixStyle::Vert => ("|", "|"),
                MatrixStyle::Plain | MatrixStyle::Ladder | MatrixStyle::ShortLadder => ("", ""),
            };
            if !bracket_chars.0.is_empty() {
                draw_stretch_bracket(svg, bracket_chars.0, x, y, fs * 0.3, lb.height, color, fs);
                draw_stretch_bracket(
                    svg,
                    bracket_chars.1,
                    x + lb.width - fs * 0.3,
                    y,
                    fs * 0.3,
                    lb.height,
                    color,
                    fs,
                );
            }
            // 셀 내용
            for row in cells {
                for cell in row {
                    render_box(svg, cell, x, y, color, fs, italic, bold);
                }
            }
        }
        LayoutKind::Rel { arrow, over, under } => {
            render_box(svg, over, x, y, color, fs, italic, bold);
            render_box(svg, arrow, x, y, color, fs, italic, bold);
            if let Some(u) = under {
                render_box(svg, u, x, y, color, fs, italic, bold);
            }
        }
        LayoutKind::EqAlign { rows } => {
            for (left, right) in rows {
                render_box(svg, left, x, y, color, fs, italic, bold);
                render_box(svg, right, x, y, color, fs, italic, bold);
            }
        }
        LayoutKind::Paren {
            left,
            right,
            left_width,
            right_width,
            delimiter_height,
            glyph_delimiters,
            left_outline,
            right_outline,
            body,
        } => {
            // 텍스트 높이 파렌(`(`, `)`)은 폰트 글리프로 렌더, 그 외는 path. (Task #283)
            let use_glyph = *glyph_delimiters;
            // 왼쪽 괄호
            if !left.is_empty() {
                if let Some(commands) = left_outline {
                    let path = super::multiplication_outline::path_data(commands);
                    svg.push_str(&format!("<path d=\"{path}\" transform=\"translate({x:.4},{y:.4})\" fill=\"{color}\"/>\n"));
                } else if use_glyph && (left == "(" || left == ")") {
                    svg.push_str(&format!(
                        "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
                        x, y + lb.baseline, fs, color, EQ_FONT_FAMILY, escape_xml(left),
                    ));
                } else {
                    draw_stretch_bracket(
                        svg,
                        left,
                        x,
                        y,
                        *left_width,
                        *delimiter_height,
                        color,
                        fs,
                    );
                }
            }
            // 본체
            render_box(svg, body, x, y, color, fs, italic, bold);
            // 오른쪽 괄호
            if !right.is_empty() {
                let right_x = x + lb.width - right_width;
                if let Some(commands) = right_outline {
                    let path = super::multiplication_outline::path_data(commands);
                    svg.push_str(&format!("<path d=\"{path}\" transform=\"translate({right_x:.4},{y:.4})\" fill=\"{color}\"/>\n"));
                } else if use_glyph && (right == "(" || right == ")") {
                    svg.push_str(&format!(
                        "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\"{}>{}</text>\n",
                        right_x, y + lb.baseline, fs, color, EQ_FONT_FAMILY, escape_xml(right),
                    ));
                } else {
                    draw_stretch_bracket(
                        svg,
                        right,
                        right_x,
                        y,
                        *right_width,
                        *delimiter_height,
                        color,
                        fs,
                    );
                }
            }
        }
        LayoutKind::Decoration {
            kind,
            body,
            negation,
            outline,
        } => {
            render_box(svg, body, x, y, color, fs, italic, bold);
            if let Some(commands) = outline {
                svg.push_str(&format!(
                    "<path d=\"{}\" transform=\"translate({x:.4},{y:.4})\" fill=\"{color}\"/>\n",
                    super::multiplication_outline::path_data(commands),
                ));
            } else if *kind == DecoKind::StrikeThrough {
                let g = negation
                    .clone()
                    .unwrap_or_else(|| super::negation_geometry::geometry(body));
                svg.push_str(&format!(
                    "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                    x + g.start.0, y + g.start.1, x + g.end.0, y + g.end.1, color, g.thickness,
                ));
            } else if *kind == DecoKind::Box {
                svg.push_str(&format!(
                    "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                    x, y, lb.width, lb.height, color, fs * 0.03,
                ));
            } else {
                let deco_y = y + fs * 0.05;
                let mid_x = x + body.x + body.width / 2.0;
                draw_decoration(svg, *kind, mid_x, deco_y, body.width, color, fs);
            }
        }
        LayoutKind::Color { rgb, body } => {
            let body_color = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]);
            render_box(svg, body, x, y, &body_color, fs, italic, bold);
        }
        LayoutKind::FontStyle { style, body } => {
            let (new_italic, new_bold) = match style {
                FontStyleKind::Roman | FontStyleKind::SansSerif | FontStyleKind::Monospace => {
                    (false, false)
                }
                FontStyleKind::Italic => (true, bold),
                FontStyleKind::Bold => (italic, true),
                FontStyleKind::Blackboard => (false, true),
                FontStyleKind::Calligraphy | FontStyleKind::Fraktur => (false, false),
            };
            render_box(svg, body, x, y, color, fs, new_italic, new_bold);
        }
        LayoutKind::Space(_) | LayoutKind::Newline | LayoutKind::Empty => {}
    }
}

/// 공개 표시 글꼴의 적분 윤곽을 공통 ink 영역에 배치한다.
/// 측정에서 정한 점유와 첨자 원점을 유지하며 모든 backend에 같은 경로를 전달한다.
pub(crate) fn integral_path_data(x: f64, y: f64, fs: f64) -> String {
    use super::integral_outline::{commands, Command};
    use std::fmt::Write;
    let mut path = String::new();
    for command in commands(x, y, fs) {
        match command {
            Command::Move((x, y)) => {
                let _ = write!(path, "M{x:.4},{y:.4}");
            }
            Command::Line((x, y)) => {
                let _ = write!(path, "L{x:.4},{y:.4}");
            }
            Command::Cubic([(a, b), (c, d), (e, f)]) => {
                let _ = write!(path, "C{a:.4},{b:.4} {c:.4},{d:.4} {e:.4},{f:.4}");
            }
            Command::Close => path.push('Z'),
        }
    }
    path
}

fn integral_path(x: f64, y: f64, fs: f64, color: &str) -> String {
    format!(
        "<path d=\"{}\" fill=\"{}\"/>\n",
        integral_path_data(x, y, fs),
        color
    )
}

fn font_size_from_box(lb: &LayoutBox, base_fs: f64) -> f64 {
    // 박스 높이에서 폰트 크기 추정 (baseline 비율로)
    if lb.height > 0.0 {
        lb.height
    } else {
        base_fs
    }
}

/// 늘림 괄호 렌더링
fn draw_stretch_bracket(
    svg: &mut String,
    bracket: &str,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    color: &str,
    fs: f64,
) {
    if matches!(bracket, "{" | "}") {
        let commands = super::brace_stretch::commands(x, y, w, h, fs, bracket == "}");
        svg.push_str(&format!(
            "<path d=\"{}\" fill=\"{}\"/>\n",
            super::multiplication_outline::path_data(&commands),
            color
        ));
        return;
    }
    let mid_x = x + w / 2.0;
    let stroke_w = if matches!(bracket, "(" | ")") {
        (fs * 0.042).max(0.48)
    } else {
        fs * 0.04
    };

    match bracket {
        "(" => {
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} C{:.2},{:.2} {:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\" stroke-linecap=\"round\"/>\n",
                x + w * 0.9, y,
                x + w * 0.05, y + h * 0.18,
                x + w * 0.05, y + h * 0.82,
                x + w * 0.9, y + h,
                color, stroke_w,
            ));
        }
        ")" => {
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} C{:.2},{:.2} {:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\" stroke-linecap=\"round\"/>\n",
                x + w * 0.1, y,
                x + w * 0.95, y + h * 0.18,
                x + w * 0.95, y + h * 0.82,
                x + w * 0.1, y + h,
                color, stroke_w,
            ));
        }
        "[" => {
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x + w * 0.2, y,
                mid_x - w * 0.2, y,
                mid_x - w * 0.2, y + h,
                mid_x + w * 0.2, y + h,
                color, stroke_w,
            ));
        }
        "]" => {
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - w * 0.2, y,
                mid_x + w * 0.2, y,
                mid_x + w * 0.2, y + h,
                mid_x - w * 0.2, y + h,
                color, stroke_w,
            ));
        }
        "|" => {
            svg.push_str(&format!(
                "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x, y, mid_x, y + h, color, stroke_w,
            ));
        }
        _ => {
            // 기타 문자 (⌈, ⌉, ⌊, ⌋ 등)은 텍스트로 렌더링
            let esc = escape_xml(bracket);
            svg.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" font-size=\"{:.2}\" fill=\"{}\" text-anchor=\"middle\"{}>{}</text>\n",
                mid_x, y + h * 0.7, h, color, EQ_FONT_FAMILY, esc,
            ));
        }
    }
}

/// 장식 렌더링
fn draw_decoration(
    svg: &mut String,
    kind: DecoKind,
    mid_x: f64,
    y: f64,
    width: f64,
    color: &str,
    fs: f64,
) {
    let stroke_w = fs * 0.03;
    let half_w = width / 2.0;

    match kind {
        DecoKind::Hat => {
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - half_w * 0.6, y + fs * 0.15,
                mid_x, y,
                mid_x + half_w * 0.6, y + fs * 0.15,
                color, stroke_w,
            ));
        }
        DecoKind::Bar | DecoKind::Overline => {
            svg.push_str(&format!(
                "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - half_w, y + fs * 0.05,
                mid_x + half_w, y + fs * 0.05,
                color, stroke_w,
            ));
        }
        DecoKind::Vec | DecoKind::Dyad => {
            // 오른쪽 화살표 (dyad 는 왼쪽 화살촉도 그린다)
            let arrow_y = y + fs * 0.05;
            svg.push_str(&format!(
                "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - half_w, arrow_y,
                mid_x + half_w, arrow_y,
                color, stroke_w,
            ));
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x + half_w - fs * 0.1, arrow_y - fs * 0.06,
                mid_x + half_w, arrow_y,
                mid_x + half_w - fs * 0.1, arrow_y + fs * 0.06,
                color, stroke_w,
            ));
            if kind == DecoKind::Dyad {
                svg.push_str(&format!(
                    "<path d=\"M{:.2},{:.2} L{:.2},{:.2} L{:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                    mid_x - half_w + fs * 0.1, arrow_y - fs * 0.06,
                    mid_x - half_w, arrow_y,
                    mid_x - half_w + fs * 0.1, arrow_y + fs * 0.06,
                    color, stroke_w,
                ));
            }
        }
        DecoKind::Tilde => {
            let ty = y + fs * 0.08;
            svg.push_str(&format!(
                "<path d=\"M{:.2},{:.2} Q{:.2},{:.2} {:.2},{:.2} Q{:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - half_w * 0.6, ty,
                mid_x - half_w * 0.2, ty - fs * 0.08,
                mid_x, ty,
                mid_x + half_w * 0.2, ty + fs * 0.08,
                mid_x + half_w * 0.6, ty,
                color, stroke_w,
            ));
        }
        DecoKind::Dot => {
            svg.push_str(&format!(
                "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"{}\"/>\n",
                mid_x,
                y + fs * 0.06,
                fs * 0.03,
                color,
            ));
        }
        DecoKind::DDot => {
            let gap = fs * 0.1;
            svg.push_str(&format!(
                "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"{}\"/>\n",
                mid_x - gap,
                y + fs * 0.06,
                fs * 0.03,
                color,
            ));
            svg.push_str(&format!(
                "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"{}\"/>\n",
                mid_x + gap,
                y + fs * 0.06,
                fs * 0.03,
                color,
            ));
        }
        DecoKind::Underline | DecoKind::Under => {
            // 아래선은 y 위치를 body 아래로 옮김 (여기서는 위치만 표시)
            // 실제로는 body 높이를 알아야 하지만, 여기서는 근사치 사용
            let uy = y + fs * 1.1;
            svg.push_str(&format!(
                "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - half_w, uy, mid_x + half_w, uy, color, stroke_w,
            ));
        }
        _ => {
            // Check, Acute, Grave, Arch 등 간략 처리
            svg.push_str(&format!(
                "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                mid_x - half_w * 0.5, y + fs * 0.1,
                mid_x + half_w * 0.5, y + fs * 0.1,
                color, stroke_w,
            ));
        }
    }
}

/// XML 특수문자 이스케이프
fn escape_xml(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => result.push_str("&amp;"),
            '<' => result.push_str("&lt;"),
            '>' => result.push_str("&gt;"),
            '"' => result.push_str("&quot;"),
            '\'' => result.push_str("&apos;"),
            // XML 1.0 허용 문자: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
            // 그 외(제어문자, U+FFFE, U+FFFF 등)는 제거 — 방출된 SVG 가 불법 XML 이 되지 않도록 (#3382)
            '\u{09}' | '\u{0A}' | '\u{0D}' => result.push(ch),
            '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
                result.push(ch)
            }
            _ => {} // XML 무효 문자 제거
        }
    }
    result
}

/// 수식 color(0x00BBGGRR)를 SVG 색상 문자열(#rrggbb)로 변환
pub fn eq_color_to_svg(color: u32) -> String {
    let r = color & 0xFF;
    let g = (color >> 8) & 0xFF;
    let b = (color >> 16) & 0xFF;
    format!("#{:02x}{:02x}{:02x}", r, g, b)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::renderer::equation::layout::EqLayout;
    use crate::renderer::equation::parser::EqParser;
    use crate::renderer::equation::tokenizer::tokenize;

    fn render_eq(script: &str) -> String {
        let tokens = tokenize(script);
        let ast = EqParser::new(tokens).parse();
        let layout = EqLayout::new(20.0).layout(&ast);
        render_equation_svg(&layout, "#000000", 20.0)
    }

    /// 분리된 글리프도 실제 SVG 텍스트 노드의 순서로 검사한다.
    fn rendered_text(svg: &str) -> String {
        let wrapped = format!("<svg>{svg}</svg>");
        let document = roxmltree::Document::parse(&wrapped).expect("유효한 수식 SVG");
        document
            .descendants()
            .filter(|node| node.has_tag_name("text"))
            .filter_map(|node| node.text())
            .collect()
    }

    #[test]
    fn escape_xml_drops_xml_invalid_control_chars() {
        // #3382: 수식 SVG 는 본문 SVG(renderer/svg.rs)와 달리 XML 1.0 문자 필터가 없어,
        // IR 텍스트에 섞인 제어문자를 그대로 방출하면 산출 SVG 가 불법 XML 이 된다
        // ("PCDATA invalid Char value 3") — 뷰어가 해당 페이지 렌더를 중단한다.
        assert_eq!(escape_xml("a\u{03}b"), "ab");
        for c in ['\u{00}', '\u{08}', '\u{0B}', '\u{0C}', '\u{0E}', '\u{1F}'] {
            assert_eq!(
                escape_xml(&format!("x{c}y")),
                "xy",
                "control {:#04x}",
                c as u32
            );
        }
        assert_eq!(escape_xml("a\u{FFFE}\u{FFFF}b"), "ab");
        // 탭·개행·복귀는 XML 1.0 허용 문자이므로 유지
        assert_eq!(escape_xml("a\tb\nc\rd"), "a\tb\nc\rd");
        // 기존 마크업 이스케이프는 무회귀
        assert_eq!(escape_xml("<a & b>\"'"), "&lt;a &amp; b&gt;&quot;&apos;");
    }

    #[test]
    fn test_simple_text_svg() {
        let svg = render_eq("abc");
        assert!(svg.contains("<text"));
        assert_eq!(
            rendered_text(&svg),
            "𝑎𝑏𝑐",
            "변수 내용·순서·이탤릭 글리프 보존"
        );
    }

    #[test]
    fn test_fraction_svg() {
        let svg = render_eq("a over b");
        assert!(svg.contains("<text")); // 분자/분모 텍스트
        assert!(svg.contains("<line")); // 분수선
    }

    #[test]
    fn test_atop_svg_has_no_fraction_line() {
        let svg = render_eq("a atop b");
        assert!(svg.contains("<text"));
        assert!(!svg.contains("<line"));
        let y_values: Vec<&str> = svg
            .lines()
            .filter_map(|line| line.split(" y=\"").nth(1))
            .filter_map(|rest| rest.split('"').next())
            .collect();
        assert_eq!(
            y_values.len(),
            2,
            "ATOP은 위/아래 텍스트 2개를 렌더링해야 함: {}",
            svg
        );
        assert_ne!(
            y_values[0], y_values[1],
            "ATOP은 두 항을 세로로 배치해야 함: {}",
            svg
        );
    }

    #[test]
    fn test_paren_svg() {
        // 텍스트 높이 파렌은 글리프로 렌더 (Task #283)
        let svg = render_eq("LEFT ( a RIGHT )");
        assert!(svg.contains("<text")); // 내용 + 글리프 파렌
        assert!(!svg.contains("<path")); // path 파렌 아님
    }

    #[test]
    fn test_paren_stretch_svg() {
        // 스트레치 파렌(분수 감쌈)은 path 유지 (Task #283)
        let svg = render_eq("LEFT ( a over b RIGHT )");
        assert!(svg.contains("<path")); // 스트레치 괄호
        assert!(svg.contains(" C")); // 둥근 괄호는 완만한 cubic 곡선으로 렌더
        assert!(svg.contains("stroke-linecap=\"round\""));
        assert!(svg.contains("<line")); // 분수선
    }

    #[test]
    fn test_issue_1139_integral_left_right_parens_are_curved() {
        let svg = render_eq(" int _{0} ^{pi } {} x`cos LEFT ( {pi } over {2} -x RIGHT ) dx");
        // Task #1317: 적분 기호는 폰트 text(∫) 가 아닌 stroke path 로 렌더된다.
        assert!(
            !svg.contains(">∫<"),
            "적분 기호는 path 로 렌더되어야 함(text ∫ 아님): {}",
            svg
        );
        assert!(
            svg.contains("<path"),
            "적분 기호가 path 로 렌더되어야 함: {}",
            svg
        );
        assert!(svg.contains(">cos<"), "cos 함수가 렌더링되어야 함: {}", svg);
        assert!(
            rendered_text(&svg).contains('𝜋'),
            "pi 명령의 이탤릭 수학 글리프가 보존되어야 함: {}",
            svg
        );
        assert!(
            svg.contains(" C"),
            "큰 둥근 괄호는 cubic path여야 함: {}",
            svg
        );
        assert!(
            !svg.contains(">LEFT<"),
            "LEFT 명령이 문자로 새면 안 됨: {}",
            svg
        );
        assert!(
            !svg.contains(">RIGHT<"),
            "RIGHT 명령이 문자로 새면 안 됨: {}",
            svg
        );
    }

    #[test]
    fn test_eq01_svg() {
        let svg = render_eq(
            "평점=입찰가격평가~배점한도 TIMES LEFT ( {최저입찰가격} over {해당입찰가격} RIGHT )",
        );
        assert!(svg.contains("평점"));
        assert!(svg.contains("×")); // TIMES → ×
        assert!(svg.contains("<line")); // 분수선
        assert!(svg.contains("<path")); // 괄호
    }

    // Task #488: rm/it 폰트 스타일 적용 검증

    #[test]
    fn test_default_text_is_italic() {
        // 독립 한컴 Print의 기본 변수는 이탤릭이다. Unicode 수학 글리프도 같은 의미다.
        let svg = render_eq("K");
        assert!(rendered_text(&svg) == "𝐾", "기본 변수는 italic: {}", svg);
    }

    #[test]
    fn test_rm_disables_italic() {
        // rm K (직립체): italic 미적용
        let svg = render_eq("rm K");
        assert!(
            !svg.contains("font-style=\"italic\""),
            "rm 적용 시 italic 없음: {}",
            svg
        );
        assert!(svg.contains(">K<"));
    }

    #[test]
    fn test_rm_prefix_form_disables_italic() {
        // rmK (공백 없는 prefix 형태): italic 미적용
        let svg = render_eq("rmK");
        assert!(
            !svg.contains("font-style=\"italic\""),
            "rmK 적용 시 italic 없음: {}",
            svg
        );
        assert!(svg.contains(">K<"));
        // rm prefix 자체가 토큰으로 분리되었으므로 raw "rmK" 가 SVG 텍스트로 남지 않아야 함
        assert!(!svg.contains(">rmK<"));
    }

    #[test]
    fn test_rm_compound_chemical_symbol() {
        // rmCa: 두 글자 화학 기호도 한 토큰으로 묶여 italic 미적용
        let svg = render_eq("rmCa");
        assert!(!svg.contains("font-style=\"italic\""));
        assert!(svg.contains(">Ca<"));
    }

    #[test]
    fn test_it_keeps_italic() {
        // 명시 이탤릭은 CSS 속성 유무 대신 실제 이탤릭 수학 글리프를 검사한다.
        let svg = render_eq("it K");
        assert_eq!(rendered_text(&svg), "𝐾");
    }

    #[test]
    fn test_cjk_never_italic() {
        // 한글은 default italic=true 영역에서도 italic 미적용
        let svg = render_eq("평점");
        assert!(
            !svg.contains("font-style=\"italic\""),
            "CJK는 italic 미적용: {}",
            svg
        );
        assert!(svg.contains("평점"));
    }
}