rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
//! 그림 삽입/속성/crop native 명령 (object_ops 분할, #1904).

use super::MIN_SHAPE_SIZE;
use crate::document_core::helpers::{get_textbox_from_shape, get_textbox_from_shape_mut};
use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;
use crate::model::paragraph::Paragraph;
use crate::model::shape::{common_obj_offsets, ShapeObject};

/// [Issue #6204] 어울림 배제 밴드를 결정하는 개체 기하의 지문.
///
/// 이 값이 그대로면 밴드도 그대로이므로 저장 `LINE_SEG` 를 다시 새길 필요가 없다.
/// 밴드는 **위치·크기·기준·정렬·어울림 종류·바깥 여백**이 함께 정하므로 전부 넣는다.
/// 글자처럼 취급(`treat_as_char`)은 밴드를 만들지 않지만, 그 토글 자체가 밴드의
/// 유무를 바꾸므로 포함한다.
/// [#8399] 어울림 도형도 같은 밴드를 만든다 — 도형 속성 편집이 같은 지문을 쓴다.
#[derive(PartialEq, Eq)]
pub(super) struct PictureBandGeometry {
    horizontal_offset: i32,
    vertical_offset: i32,
    width: u32,
    height: u32,
    horz_rel_to: u8,
    vert_rel_to: u8,
    horz_align: u8,
    vert_align: u8,
    treat_as_char: bool,
    text_wrap: u8,
    margin: (i16, i16, i16, i16),
}

pub(super) fn picture_band_geometry(
    common: &crate::model::shape::CommonObjAttr,
) -> PictureBandGeometry {
    PictureBandGeometry {
        horizontal_offset: common.horizontal_offset as i32,
        vertical_offset: common.vertical_offset as i32,
        width: common.width,
        height: common.height,
        horz_rel_to: common.horz_rel_to as u8,
        vert_rel_to: common.vert_rel_to as u8,
        horz_align: common.horz_align as u8,
        vert_align: common.vert_align as u8,
        treat_as_char: common.treat_as_char,
        text_wrap: common.text_wrap as u8,
        margin: (
            common.margin.left,
            common.margin.right,
            common.margin.top,
            common.margin.bottom,
        ),
    }
}

impl DocumentCore {
    fn resolve_picture_control_ref(
        &self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
    ) -> Result<&crate::model::image::Picture, HwpError> {
        let section = self.document.sections.get(section_idx).ok_or_else(|| {
            HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
        })?;

        let body_len = section.paragraphs.len();
        let para = if parent_para_idx < body_len {
            section.paragraphs.get(parent_para_idx).ok_or_else(|| {
                HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
            })?
        } else {
            let mut virtual_idx = parent_para_idx - body_len;
            let mut found = None;
            'outer: for body_para in &section.paragraphs {
                for ctrl in &body_para.controls {
                    if let Control::Endnote(en) = ctrl {
                        if virtual_idx < en.paragraphs.len() {
                            found = en.paragraphs.get(virtual_idx);
                            break 'outer;
                        }
                        virtual_idx -= en.paragraphs.len();
                    }
                }
            }
            found.ok_or_else(|| {
                HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
            })?
        };

        let ctrl = para.controls.get(control_idx).ok_or_else(|| {
            HwpError::RenderError(format!("컨트롤 인덱스 {} 범위 초과", control_idx))
        })?;
        match ctrl {
            Control::Picture(p) => Ok(p),
            Control::Shape(shape) => match shape.as_ref() {
                ShapeObject::Picture(p) => Ok(p),
                _ => Err(HwpError::RenderError(
                    "지정된 Shape 컨트롤이 그림이 아닙니다".to_string(),
                )),
            },
            _ => Err(HwpError::RenderError(
                "지정된 컨트롤이 그림이 아닙니다".to_string(),
            )),
        }
    }
    pub(crate) fn resolve_picture_control_mut(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
    ) -> Result<&mut crate::model::image::Picture, HwpError> {
        let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
            HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
        })?;

        let body_len = section.paragraphs.len();
        let para = if parent_para_idx < body_len {
            section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
                HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
            })?
        } else {
            let mut virtual_idx = parent_para_idx - body_len;
            let mut found = None;
            'outer: for body_para in &mut section.paragraphs {
                for ctrl in &mut body_para.controls {
                    if let Control::Endnote(en) = ctrl {
                        if virtual_idx < en.paragraphs.len() {
                            found = en.paragraphs.get_mut(virtual_idx);
                            break 'outer;
                        }
                        virtual_idx -= en.paragraphs.len();
                    }
                }
            }
            found.ok_or_else(|| {
                HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
            })?
        };

        let ctrl = para.controls.get_mut(control_idx).ok_or_else(|| {
            HwpError::RenderError(format!("컨트롤 인덱스 {} 범위 초과", control_idx))
        })?;
        match ctrl {
            Control::Picture(p) => Ok(p),
            Control::Shape(shape) => match shape.as_mut() {
                ShapeObject::Picture(p) => Ok(p),
                _ => Err(HwpError::RenderError(
                    "지정된 Shape 컨트롤이 그림이 아닙니다".to_string(),
                )),
            },
            _ => Err(HwpError::RenderError(
                "지정된 컨트롤이 그림이 아닙니다".to_string(),
            )),
        }
    }
    pub fn get_picture_properties_native(
        &self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
    ) -> Result<String, HwpError> {
        let pic = self.resolve_picture_control_ref(section_idx, parent_para_idx, control_idx)?;
        Self::format_picture_properties_json(pic)
    }
    fn picture_crop_extent_hu(pic: &crate::model::image::Picture) -> (i32, i32) {
        let width = if pic.shape_attr.original_width > 0 {
            pic.shape_attr.original_width
        } else {
            pic.shape_attr.current_width
        };
        let height = if pic.shape_attr.original_height > 0 {
            pic.shape_attr.original_height
        } else {
            pic.shape_attr.current_height
        };
        (
            i32::try_from(width).unwrap_or(i32::MAX),
            i32::try_from(height).unwrap_or(i32::MAX),
        )
    }
    fn picture_crop_ui_amounts(pic: &crate::model::image::Picture) -> (i32, i32, i32, i32) {
        let (extent_w, extent_h) = Self::picture_crop_extent_hu(pic);
        let left = pic.crop.left.max(0);
        let top = pic.crop.top.max(0);
        let right = if extent_w > 0 && pic.crop.right > left {
            (extent_w - pic.crop.right).max(0)
        } else {
            0
        };
        let bottom = if extent_h > 0 && pic.crop.bottom > top {
            (extent_h - pic.crop.bottom).max(0)
        } else {
            0
        };
        (left, top, right, bottom)
    }
    fn set_picture_crop_from_ui_amounts(
        pic: &mut crate::model::image::Picture,
        left: i32,
        top: i32,
        right: i32,
        bottom: i32,
    ) {
        let (extent_w, extent_h) = Self::picture_crop_extent_hu(pic);
        pic.crop.left = left.max(0);
        pic.crop.top = top.max(0);
        if extent_w > 0 {
            pic.crop.right = (extent_w - right.max(0)).max(pic.crop.left);
        } else {
            pic.crop.right = right.max(0);
        }
        if extent_h > 0 {
            pic.crop.bottom = (extent_h - bottom.max(0)).max(pic.crop.top);
        } else {
            pic.crop.bottom = bottom.max(0);
        }
    }
    /// [#5890] 변환 파생 상태(`raw_rendering`·render_*)의 무효화 판정 근거.
    ///
    /// 종전에는 props JSON 에 변환 키가 **등장하는지**만 텍스트로 훑어
    /// (`"width"`·`"height"`·`"vertOffset"`·`"horzOffset"`·`"rotationAngle"`·
    /// `"horzFlip"`·`"vertFlip"`) 같은 값을 다시 지정하기만 해도 한컴 원본
    /// 렌더링 행렬을 파괴했다 — getter 가 낸 봉지를 그대로 재적용해도 마찬가지였다.
    /// 그 키들이 실제로 쓰는 IR 필드를 지문으로 떠서 값 변화로 판정한다.
    fn picture_transform_fingerprint(
        pic: &crate::model::image::Picture,
    ) -> (u32, u32, u32, u32, u32, u32, i16, bool, bool) {
        // [#6740] 판정은 도형 경로와 공용이다 — 둘이 갈라지면 같은 결함이 한쪽에만 남는다.
        super::common::shape_transform_fingerprint(&pic.common, &pic.shape_attr)
    }
    pub(crate) fn picture_rotated_bounds(width: u32, height: u32, angle: i16) -> (u32, u32) {
        if width == 0 || height == 0 || angle.rem_euclid(360) == 0 {
            return (width, height);
        }

        let theta = (angle as f64).to_radians();
        let cos = theta.cos().abs();
        let sin = theta.sin().abs();
        let rotated_width = width as f64 * cos + height as f64 * sin;
        let rotated_height = width as f64 * sin + height as f64 * cos;
        (
            rotated_width.round().max(1.0) as u32,
            rotated_height.round().max(1.0) as u32,
        )
    }
    fn refresh_picture_rotation_layout_for_save(pic: &mut crate::model::image::Picture) {
        let cur_w = if pic.shape_attr.current_width > 0 {
            pic.shape_attr.current_width
        } else {
            pic.common.width
        };
        let cur_h = if pic.shape_attr.current_height > 0 {
            pic.shape_attr.current_height
        } else {
            pic.common.height
        };

        if cur_w == 0 || cur_h == 0 {
            return;
        }

        pic.shape_attr.current_width = cur_w;
        pic.shape_attr.current_height = cur_h;

        let old_center_x =
            pic.common.horizontal_offset as i32 as i64 + (pic.common.width as i64 / 2);
        let old_center_y =
            pic.common.vertical_offset as i32 as i64 + (pic.common.height as i64 / 2);
        let (bbox_w, bbox_h) =
            Self::picture_rotated_bounds(cur_w, cur_h, pic.shape_attr.rotation_angle);

        if pic.shape_attr.rotation_angle.rem_euclid(360) != 0 {
            pic.common.width = bbox_w;
            pic.common.height = bbox_h;
            pic.common.horizontal_offset = (old_center_x - (bbox_w as i64 / 2)) as i32 as u32;
            pic.common.vertical_offset = (old_center_y - (bbox_h as i64 / 2)) as i32 as u32;
        } else {
            pic.common.width = cur_w;
            pic.common.height = cur_h;
            pic.common.horizontal_offset = (old_center_x - (cur_w as i64 / 2)) as i32 as u32;
            pic.common.vertical_offset = (old_center_y - (cur_h as i64 / 2)) as i32 as u32;
        }

        pic.shape_attr.rotation_center.x = (pic.common.width / 2) as i32;
        pic.shape_attr.rotation_center.y = (pic.common.height / 2) as i32;
        // `rotate_image` 와 `flip` bit19(0x0008_0000)는 **여기서 건드리지 않는다.**
        // 종전에는 각도와 무관하게 둘을 세웠고, 회전을 0 으로 되돌려도 남아 되돌릴 경로가
        // 없었다. 한컴 오라클(`tools/hangul_rotation_oracle/EVIDENCE.md`)이 잰 결과 둘은
        // 회전 상태의 함수가 아니다:
        //   - 한컴 저장본 5660개 개체에서 bit19 는 회전 개체 569건 중 559건이 **꺼져** 있고
        //     비회전 개체 5091건 중 4416건이 **켜져** 있다(회전과 반대 방향).
        //   - 한글 2024 는 회전 0 그림의 bit19 를 그대로 켜 두고, 34° 회전 그림의
        //     `rotateimage` 를 0 으로 둔다.
        // 세우는 것도 지우는 것도 근거가 없으므로 파싱된 값을 보존한다. HWP5 저장에는
        // `flip` 만 나가고 `rotate_image` 는 HWPX `rotateimage` 의 원천이다.
    }
    fn apply_picture_display_width(pic: &mut crate::model::image::Picture, width: u32) {
        let old_common_width = pic.common.width;
        let old_current_width = pic.shape_attr.current_width;
        pic.common.width = width;
        if pic.shape_attr.rotation_angle.rem_euclid(360) != 0
            && old_common_width > 0
            && old_current_width > 0
        {
            pic.shape_attr.current_width =
                ((old_current_width as f64 * width as f64 / old_common_width as f64).round())
                    .max(1.0) as u32;
        } else {
            pic.shape_attr.current_width = width;
        }
    }
    fn apply_picture_display_height(pic: &mut crate::model::image::Picture, height: u32) {
        let old_common_height = pic.common.height;
        let old_current_height = pic.shape_attr.current_height;
        pic.common.height = height;
        if pic.shape_attr.rotation_angle.rem_euclid(360) != 0
            && old_common_height > 0
            && old_current_height > 0
        {
            pic.shape_attr.current_height =
                ((old_current_height as f64 * height as f64 / old_common_height as f64).round())
                    .max(1.0) as u32;
        } else {
            pic.shape_attr.current_height = height;
        }
    }
    /// [Task #825] 머리말/꼬리말 안 그림의 속성 조회.
    /// path: section[si].paragraphs[outer_para].controls[outer_ctrl] = Header/Footer
    ///       → .paragraphs[inner_para].controls[inner_ctrl] = Picture
    pub fn get_header_footer_picture_properties_native(
        &self,
        section_idx: usize,
        outer_para_idx: usize,
        outer_control_idx: usize,
        inner_para_idx: usize,
        inner_control_idx: usize,
    ) -> Result<String, HwpError> {
        let section = self.document.sections.get(section_idx).ok_or_else(|| {
            HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
        })?;
        let outer_para = section.paragraphs.get(outer_para_idx).ok_or_else(|| {
            HwpError::RenderError(format!("외부 문단 인덱스 {} 범위 초과", outer_para_idx))
        })?;
        let outer_ctrl = outer_para.controls.get(outer_control_idx).ok_or_else(|| {
            HwpError::RenderError(format!(
                "외부 컨트롤 인덱스 {} 범위 초과",
                outer_control_idx
            ))
        })?;

        let inner_paras: &[crate::model::paragraph::Paragraph] = match outer_ctrl {
            crate::model::control::Control::Header(h) => &h.paragraphs,
            crate::model::control::Control::Footer(f) => &f.paragraphs,
            _ => {
                return Err(HwpError::RenderError(
                    "외부 컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
                ))
            }
        };

        let inner_para = inner_paras.get(inner_para_idx).ok_or_else(|| {
            HwpError::RenderError(format!("내부 문단 인덱스 {} 범위 초과", inner_para_idx))
        })?;
        let inner_ctrl = inner_para.controls.get(inner_control_idx).ok_or_else(|| {
            HwpError::RenderError(format!(
                "내부 컨트롤 인덱스 {} 범위 초과",
                inner_control_idx
            ))
        })?;

        let pic = match inner_ctrl {
            crate::model::control::Control::Picture(p) => p,
            _ => {
                return Err(HwpError::RenderError(
                    "지정된 내부 컨트롤이 그림이 아닙니다".to_string(),
                ))
            }
        };
        Self::format_picture_properties_json(pic)
    }
    pub(crate) fn format_picture_properties_json(
        pic: &crate::model::image::Picture,
    ) -> Result<String, HwpError> {
        let c = &pic.common;
        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 effect = match pic.image_attr.effect {
            crate::model::image::ImageEffect::RealPic => "RealPic",
            crate::model::image::ImageEffect::GrayScale => "GrayScale",
            crate::model::image::ImageEffect::BlackWhite => "BlackWhite",
            crate::model::image::ImageEffect::Pattern8x8 => "Pattern8x8",
        };
        // description 내 JSON 제어 문자 이스케이프
        let desc_escaped = crate::document_core::helpers::json_escape(&c.description);
        // [Task #741 후속] 외부 file path (HWP3 외부 그림) 영역 영역 dialog 표시 영역
        let external_path_field = match &pic.image_attr.external_path {
            Some(p) => format!(
                ",\"externalPath\":\"{}\"",
                crate::document_core::helpers::json_escape(p)
            ),
            None => String::new(),
        };

        let sa = &pic.shape_attr;
        let (crop_left, crop_top, crop_right, crop_bottom) = Self::picture_crop_ui_amounts(pic);

        Ok(format!(
            concat!(
                "{{\"width\":{},\"height\":{},\"treatAsChar\":{},",
                "\"vertRelTo\":\"{}\",\"vertAlign\":\"{}\",",
                "\"horzRelTo\":\"{}\",\"horzAlign\":\"{}\",",
                "\"vertOffset\":{},\"horzOffset\":{},",
                "\"textWrap\":\"{}\",\"restrictInPage\":{},\"allowOverlap\":{},\"sizeProtect\":{},",
                "\"brightness\":{},\"contrast\":{},\"effect\":\"{}\",\"transparency\":{},",
                "\"description\":\"{}\",",
                // 회전/대칭
                "\"rotationAngle\":{},\"horzFlip\":{},\"vertFlip\":{},",
                // 원본 크기
                "\"originalWidth\":{},\"originalHeight\":{},",
                // 자르기
                "\"cropLeft\":{},\"cropTop\":{},\"cropRight\":{},\"cropBottom\":{},",
                // 안쪽 여백 (그림 여백)
                "\"paddingLeft\":{},\"paddingTop\":{},\"paddingRight\":{},\"paddingBottom\":{},",
                // 바깥 여백
                "\"outerMarginLeft\":{},\"outerMarginTop\":{},\"outerMarginRight\":{},\"outerMarginBottom\":{},",
                // 테두리
                "\"borderColor\":{},\"borderWidth\":{},",
                // 캡션
                "\"hasCaption\":{},\"captionDirection\":\"{}\",\"captionVertAlign\":\"{}\",",
                "\"captionWidth\":{},\"captionSpacing\":{},\"captionMaxWidth\":{},\"captionIncludeMargin\":{}{}}}"
            ),
            c.width, c.height, c.treat_as_char,
            vert_rel, vert_align,
            horz_rel, horz_align,
            c.vertical_offset as i32, c.horizontal_offset as i32,
            text_wrap, c.flow_with_text, c.allow_overlap, c.size_protect,
            pic.image_attr.brightness,
            pic.image_attr.contrast,
            effect,
            pic.image_attr.clamped_transparency(),
            desc_escaped,
            // 회전/대칭
            sa.rotation_angle, sa.horz_flip, sa.vert_flip,
            // 원본 크기
            sa.original_width, sa.original_height,
            // 자르기
            crop_left, crop_top, crop_right, crop_bottom,
            // 안쪽 여백
            pic.padding.left, pic.padding.top, pic.padding.right, pic.padding.bottom,
            // 바깥 여백
            c.margin.left, c.margin.top, c.margin.right, c.margin.bottom,
            // 테두리
            pic.border_color, pic.border_width,
            // 캡션
            pic.caption.is_some(),
            pic.caption.as_ref().map_or("Bottom", |cap| match cap.direction {
                crate::model::shape::CaptionDirection::Left => "Left",
                crate::model::shape::CaptionDirection::Right => "Right",
                crate::model::shape::CaptionDirection::Top => "Top",
                crate::model::shape::CaptionDirection::Bottom => "Bottom",
            }),
            pic.caption.as_ref().map_or("Top", |cap| match cap.vert_align {
                crate::model::shape::CaptionVertAlign::Top => "Top",
                crate::model::shape::CaptionVertAlign::Center => "Center",
                crate::model::shape::CaptionVertAlign::Bottom => "Bottom",
            }),
            pic.caption.as_ref().map_or(0u32, |cap| cap.width),
            pic.caption.as_ref().map_or(0i16, |cap| cap.spacing),
            pic.caption.as_ref().map_or(0u32, |cap| cap.max_width),
            pic.caption.as_ref().map_or(false, |cap| cap.include_margin),
            external_path_field,
        ))
    }
    /// 그림 컨트롤의 속성을 변경한다 (네이티브).
    pub fn set_picture_properties_native(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        let stored_end_before = self
            .document
            .sections
            .get(section_idx)
            .and_then(|section| section.paragraphs.get(parent_para_idx))
            .and_then(crate::renderer::composer::paragraph_flow_end);
        // JSON 파싱 (serde_json 사용 대신 수동 파싱 — 기존 패턴)
        // [Task #825] 픽쳐 속성 mutation 은 helper 로 분리 (머리말/꼬리말 path 와 공유).
        // [Issue #6204] 개체의 **배제 밴드 기하**를 변경 전에 찍어 둔다. 위치·크기가
        // 바뀌면 그 개체가 만드는 어울림 배제 밴드도 바뀌므로, 그 밴드에 되감긴 본문
        // 문단의 저장 `LINE_SEG` 는 더는 유효하지 않다.
        let band_geometry_before = self
            .resolve_picture_control_ref(section_idx, parent_para_idx, control_idx)
            .ok()
            .map(|pic| picture_band_geometry(&pic.common));

        let (
            caption_created,
            caption_removed,
            should_migrate_to_inline,
            should_migrate_to_floating,
        ) = {
            let pic =
                self.resolve_picture_control_mut(section_idx, parent_para_idx, control_idx)?;
            // [Task #1151 v2] tac false→true migration 검출용 snapshot.
            let was_tac = pic.common.treat_as_char;
            let had_caption = pic.caption.is_some();
            let caption_created = Self::apply_picture_props_inner(pic, props_json);
            let now_tac = pic.common.treat_as_char;
            // tac 토글이 enum 에만 반영되고 packed attr 이 낡으면 직렬화가 옛 앵커를
            // 되살린다 — 여기서 즉시 동기화 (migrate 경로는 rel_to 갱신 후 재동기화).
            crate::serializer::control::sync_anchor_bits(&mut pic.common);
            (
                caption_created,
                had_caption && pic.caption.is_none(),
                !was_tac && now_tac,
                was_tac && !now_tac,
            )
        };

        // [Task #1151 v2] floating → inline migration (H1 정합, samples/tac-verify/).
        // 한컴 산출물 Scenario A~D 분석: tac false→true 시 picture 의 control 위치는
        // 불변이다. 텍스트 없는 문단의 첫 줄은 그림 높이를 따르고, 혼합 줄은
        // 실제 소속 프레임에서 재조판한다. text/char_offsets/paragraph 수는 보존한다.
        let mut reflowed_body_end = None;
        if should_migrate_to_inline || should_migrate_to_floating {
            let styles = self.resolve_render_styles();
            let width = self.picture_host_width(section_idx, Some(parent_para_idx))?;
            let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
                HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
            })?;
            let body_len = section.paragraphs.len();
            let para = if parent_para_idx < body_len {
                section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
                    HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
                })?
            } else {
                let mut virtual_idx = parent_para_idx - body_len;
                let mut found = None;
                'outer: for body_para in &mut section.paragraphs {
                    for ctrl in &mut body_para.controls {
                        if let Control::Endnote(en) = ctrl {
                            if virtual_idx < en.paragraphs.len() {
                                found = en.paragraphs.get_mut(virtual_idx);
                                break 'outer;
                            }
                            virtual_idx -= en.paragraphs.len();
                        }
                    }
                }
                found.ok_or_else(|| {
                    HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
                })?
            };
            let style = styles.para_styles.get(para.para_shape_id as usize);
            let frame = if parent_para_idx < body_len {
                crate::renderer::composer::ParagraphBox::body_for_style(width, style, self.dpi)
            } else {
                crate::renderer::composer::ParagraphBox::content_for_style(width, style, self.dpi)
            };
            let stored_end = crate::renderer::composer::paragraph_flow_end(para);
            let has_text = !para.text.is_empty();
            if should_migrate_to_inline {
                Self::migrate_picture_floating_to_inline(
                    para,
                    control_idx,
                    frame,
                    &styles,
                    self.dpi,
                );
            } else if para.text.is_empty() && para.char_offsets.is_empty() {
                Self::migrate_empty_picture_para_inline_to_floating(para);
            } else if has_text {
                super::picture_inline_migration::reflow_text_host(para, frame, &styles, self.dpi);
            }
            if has_text && parent_para_idx < body_len {
                reflowed_body_end = Some(stored_end);
            }
        }
        if let Some(stored_end) = reflowed_body_end {
            self.finish_body_inline_object_reflow(section_idx, parent_para_idx, stored_end);
        }
        // 캡션 생성/삭제 시 자동번호를 재할당한다.
        if caption_created || caption_removed {
            crate::parser::assign_auto_numbers(&mut self.document);
        }
        // [Issue #6204] 배제 밴드 기하가 바뀌었으면 그 밴드에 되감긴 문단들의 저장
        // `LINE_SEG` 를 새 위치 기준으로 다시 새긴다.
        //
        // 종전에는 `horzOffset` 만 바뀌고 사다리는 그대로 남아, 본문이 **옛 그림
        // 위치**에 되감긴 채 굳었다(156483689 1쪽: 그림을 297.7px 로 옮겨도 줄 우단이
        // 564.5 그대로 → 그림이 글자를 덮음). 게다가 그 사다리가 파일에 실려
        // **저장 → 새로 열기로도 재현**됐다.
        //
        // 텍스트 편집이 쓰는 picture-band 재투영 경로를 그대로 태운다 — 속성 변경은
        // 이미 문서에 적용됐으므로 편집 클로저는 no-op 이고, `layout_picture_band` 가
        // **새 기하**로 밴드를 다시 계산한다. 밴드를 못 만드는 형상(그림 없음/미지원)
        // 이면 `Ok(false)` 로 조용히 지나가 종전 경로가 그대로 남는다.
        let band_geometry_after = self
            .resolve_picture_control_ref(section_idx, parent_para_idx, control_idx)
            .ok()
            .map(|pic| picture_band_geometry(&pic.common));
        if band_geometry_before != band_geometry_after {
            // 재투영 실패는 이 편집의 실패가 아니다 — 밴드를 만들 수 없는 형상이면
            // 종전대로 recompose 에 맡긴다.
            let _ = self.apply_body_edit_through_picture_band(section_idx, parent_para_idx, |_| {});
            // TAC 개체의 크기·바깥 여백 편집도 저장 줄을 다시 발행해야 한다.
            // 화면만 recompose하면 이전 줄 높이가 저장되어 재열기와 Print가 갈린다.
            if parent_para_idx < self.document.sections[section_idx].paragraphs.len()
                && self
                    .resolve_picture_control_ref(section_idx, parent_para_idx, control_idx)
                    .is_ok_and(|picture| picture.common.treat_as_char)
            {
                self.reflow_paragraph(section_idx, parent_para_idx);
                let hwp3_layout = self.document.layout_profile().hwp3_layout();
                crate::renderer::composer::recalculate_section_vpos(
                    &mut self.document.sections[section_idx].paragraphs,
                    parent_para_idx,
                    None,
                    stored_end_before,
                    &self.styles,
                    self.dpi,
                    hwp3_layout,
                );
            }
        }

        // 리플로우
        let section = &mut self.document.sections[section_idx];
        section.raw_stream = None;
        self.recompose_section(section_idx);
        self.paginate_if_needed();
        // [Task #1151 v5] page tree cache invalidate — 다른 picture/shape setter (셀 shape
        // by_path / 셀 picture by_path / header-footer picture / shape 등) 모두 호출하나
        // 본 본문 picture setter 만 누락되어 있어 studio 가 stale page tree 반환 → tac toggle
        // 후 시각 변화 없음 증상의 root cause.
        self.invalidate_page_tree_cache();
        self.event_log.push(DocumentEvent::PictureResized {
            section: section_idx,
            para: parent_para_idx,
            ctrl: control_idx,
        });
        if caption_created {
            let char_offset = self
                .resolve_picture_control_ref(section_idx, parent_para_idx, control_idx)?
                .caption
                .as_ref()
                .map_or(0, |c| {
                    c.paragraphs.first().map_or(0, |p| p.text.chars().count())
                });
            Ok(format!(
                "{{\"ok\":true,\"captionCharOffset\":{}}}",
                char_offset
            ))
        } else {
            Ok("{\"ok\":true}".to_string())
        }
    }
    /// [Task #825] 머리말/꼬리말 안 그림 속성 변경.
    /// path: section[si].paragraphs[outer_para].controls[outer_ctrl] = Header/Footer
    ///       → .paragraphs[inner_para].controls[inner_ctrl] = Picture
    /// 캡션 신규 생성은 본 함수에서 미지원 (현 dialog UI 가 머리말 picture 캡션
    /// 변경을 노출하지 않음). caption_created 검출 시 NotSupported 에러.
    pub fn set_header_footer_picture_properties_native(
        &mut self,
        section_idx: usize,
        outer_para_idx: usize,
        outer_control_idx: usize,
        inner_para_idx: usize,
        inner_control_idx: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        let styles = self.resolve_render_styles();
        let width = self.picture_host_width(section_idx, None)?;
        let caption_created;
        {
            let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
                HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
            })?;
            let outer_para = section.paragraphs.get_mut(outer_para_idx).ok_or_else(|| {
                HwpError::RenderError(format!("외부 문단 인덱스 {} 범위 초과", outer_para_idx))
            })?;
            let outer_ctrl = outer_para
                .controls
                .get_mut(outer_control_idx)
                .ok_or_else(|| {
                    HwpError::RenderError(format!(
                        "외부 컨트롤 인덱스 {} 범위 초과",
                        outer_control_idx
                    ))
                })?;
            let inner_paras: &mut Vec<crate::model::paragraph::Paragraph> = match outer_ctrl {
                crate::model::control::Control::Header(h) => &mut h.paragraphs,
                crate::model::control::Control::Footer(f) => &mut f.paragraphs,
                _ => {
                    return Err(HwpError::RenderError(
                        "외부 컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
                    ))
                }
            };
            let inner_para = inner_paras.get_mut(inner_para_idx).ok_or_else(|| {
                HwpError::RenderError(format!("내부 문단 인덱스 {} 범위 초과", inner_para_idx))
            })?;
            let inner_ctrl = inner_para
                .controls
                .get_mut(inner_control_idx)
                .ok_or_else(|| {
                    HwpError::RenderError(format!(
                        "내부 컨트롤 인덱스 {} 범위 초과",
                        inner_control_idx
                    ))
                })?;
            let pic = match inner_ctrl {
                crate::model::control::Control::Picture(p) => p,
                _ => {
                    return Err(HwpError::RenderError(
                        "지정된 내부 컨트롤이 그림이 아닙니다".to_string(),
                    ))
                }
            };
            // [Task #1151 v2] 본문 picture setter(set_picture_properties_native) 와 동일하게,
            // treatAsChar false→true/true→false 전환 시 앵커 문단의 line_segs 도 갱신해야
            // 한다. 머리말/꼬리말 경로는 이 마이그레이션이 누락되어 있었음 — tac on 시
            // 그림 높이가 줄 높이에 반영되지 않아 렌더 시 그림이 겹치거나 잘림.
            let was_tac = pic.common.treat_as_char;
            caption_created = Self::apply_picture_props_inner(pic, props_json);
            let now_tac = pic.common.treat_as_char;
            // 본문 setter 와 같은 이유로 여기서도 packed attr 을 동기화한다 —
            // 머리말/꼬리말 경로도 같은 tac 토글 마이그레이션을 수행한다 (Issue #3781).
            crate::serializer::control::sync_anchor_bits(&mut pic.common);
            let frame = crate::renderer::composer::ParagraphBox::content_for_style(
                width,
                styles.para_styles.get(inner_para.para_shape_id as usize),
                self.dpi,
            );
            if !was_tac && now_tac {
                Self::migrate_picture_floating_to_inline(
                    inner_para,
                    inner_control_idx,
                    frame,
                    &styles,
                    self.dpi,
                );
            } else if was_tac && !now_tac {
                if inner_para.text.is_empty() {
                    Self::migrate_empty_picture_para_inline_to_floating(inner_para);
                } else {
                    super::picture_inline_migration::reflow_text_host(
                        inner_para, frame, &styles, self.dpi,
                    );
                }
            }
        }
        if caption_created {
            return Err(HwpError::RenderError(
                "머리말/꼬리말 그림에 캡션 신규 생성은 본 버전에서 지원하지 않습니다".to_string(),
            ));
        }
        let section = &mut self.document.sections[section_idx];
        section.raw_stream = None;
        self.recompose_section(section_idx);
        self.paginate_if_needed();
        self.event_log.push(DocumentEvent::PictureResized {
            section: section_idx,
            para: outer_para_idx,
            ctrl: outer_control_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }
    /// TAC 그림을 자리차지 개체로 되돌릴 때, 텍스트 없는 그림 전용 문단의
    /// LINE_SEG를 남은 TAC 개체 수에 맞춰 재구성한다.
    ///
    /// 기존 false→true 마이그레이션은 첫 LINE_SEG를 그림 높이로 키운다. 반대로
    /// true→false가 되면 그 그림은 더 이상 inline 글자 슬롯이 아니므로, 같은
    /// 문단의 남은 TAC 그림만 빈 줄에 1개씩 매핑되어야 한다. 한컴 저장본
    /// `투명도0-50-2nd그림글차처럼off.hwp`처럼 TopAndBottom 예약 높이는 첫 TAC
    /// 줄의 `vertical_pos`에 반영한다.
    pub(crate) fn migrate_empty_picture_para_inline_to_floating(
        para: &mut crate::model::paragraph::Paragraph,
    ) {
        if !para.text.is_empty() || !para.char_offsets.is_empty() {
            return;
        }

        let old_seg = para.line_segs.first().cloned().unwrap_or_default();
        let line_spacing = if old_seg.line_spacing > 0 {
            old_seg.line_spacing
        } else {
            600
        };
        let reserved_hu = Self::topbottom_reserved_height_for_empty_picture_para(&para.controls);
        let tac_heights = para
            .controls
            .iter()
            .filter_map(Self::tac_control_height_for_empty_picture_para)
            .collect::<Vec<_>>();

        if tac_heights.is_empty() {
            para.line_segs = vec![crate::model::paragraph::LineSeg {
                text_start: 0,
                vertical_pos: reserved_hu,
                line_height: 1000,
                text_height: 1000,
                baseline_distance: 850,
                line_spacing,
                segment_width: old_seg.segment_width,
                column_start: old_seg.column_start,
                tag: old_seg.tag,
            }];
            return;
        }

        let mut vpos = reserved_hu;
        let mut rebuilt = Vec::with_capacity(tac_heights.len());
        for (idx, height) in tac_heights.into_iter().enumerate() {
            let line_height = height.max(1);
            rebuilt.push(crate::model::paragraph::LineSeg {
                text_start: (idx as u32) * 8,
                vertical_pos: vpos,
                line_height,
                text_height: line_height,
                baseline_distance: (line_height as f64 * 0.85).round() as i32,
                line_spacing,
                segment_width: old_seg.segment_width,
                column_start: old_seg.column_start,
                tag: old_seg.tag,
            });
            vpos += line_height + line_spacing;
        }
        para.line_segs = rebuilt;
    }
    fn tac_control_height_for_empty_picture_para(ctrl: &Control) -> Option<i32> {
        match ctrl {
            Control::Picture(pic) if pic.common.treat_as_char => Some(pic.common.height as i32),
            Control::Shape(shape) if shape.common().treat_as_char => Some(shape.flow_height_hu()),
            Control::Table(table) if table.common.treat_as_char => Some(table.common.height as i32),
            Control::Equation(eq) if eq.common.treat_as_char => Some(eq.common.height as i32),
            _ => None,
        }
    }
    fn topbottom_reserved_height_for_empty_picture_para(controls: &[Control]) -> i32 {
        controls
            .iter()
            .map(|ctrl| match ctrl {
                Control::Picture(pic)
                    if !pic.common.treat_as_char
                        && matches!(
                            pic.common.text_wrap,
                            crate::model::shape::TextWrap::TopAndBottom
                        ) =>
                {
                    pic.common.height as i32
                        + pic.common.margin.top as i32
                        + pic.common.margin.bottom as i32
                }
                Control::Shape(shape)
                    if !shape.common().treat_as_char
                        && matches!(
                            shape.common().text_wrap,
                            crate::model::shape::TextWrap::TopAndBottom
                        ) =>
                {
                    let common = shape.common();
                    common.height as i32 + common.margin.top as i32 + common.margin.bottom as i32
                }
                Control::Table(table)
                    if !table.common.treat_as_char
                        && matches!(
                            table.common.text_wrap,
                            crate::model::shape::TextWrap::TopAndBottom
                        ) =>
                {
                    table.common.height as i32
                        + table.outer_margin_top as i32
                        + table.outer_margin_bottom as i32
                }
                _ => 0,
            })
            .sum()
    }
    pub(crate) fn take_place_picture_flow_offset(
        pic: &crate::model::image::Picture,
    ) -> Option<i32> {
        if pic.common.treat_as_char
            || !matches!(
                pic.common.text_wrap,
                crate::model::shape::TextWrap::TopAndBottom
            )
            || !matches!(pic.common.vert_rel_to, crate::model::shape::VertRelTo::Para)
        {
            return None;
        }

        let visual_height = if pic.shape_attr.rotation_angle.rem_euclid(360) != 0
            && pic.shape_attr.current_width > 0
            && pic.shape_attr.current_height > 0
        {
            pic.common.height
        } else {
            let (_, height) = Self::picture_rotated_bounds(
                pic.common.width,
                pic.common.height,
                pic.shape_attr.rotation_angle,
            );
            height
        };
        Some(
            (pic.common.vertical_offset as i32)
                .saturating_add(visual_height.min(i32::MAX as u32) as i32)
                .max(0),
        )
    }
    /// [Task #825] Picture 속성 JSON 적용 (mutation only). 후처리 (AutoNumber /
    /// recompose / paginate / event log) 는 호출자 책임.
    /// 반환: caption_created (true 면 호출자가 AutoNumber 후처리 필요).
    pub(crate) fn apply_picture_props_inner(
        pic: &mut crate::model::image::Picture,
        props_json: &str,
    ) -> bool {
        use crate::document_core::helpers::{json_bool, json_i16, json_i32, json_str, json_u32};

        let transform_before = Self::picture_transform_fingerprint(pic);
        let mut rotation_changed = false;

        // 크기 변경 — [#6806] 키가 있어도 값이 같으면 건드리지 않는다. 종전에는 게터가 낸
        // 봉지를 그대로 되먹여도 `current_*` 가 `common.*` 로 덮여(파싱값이 1 어긋난 문서가
        // corpus 에 69건) 지문이 흔들리고 한컴 원본 렌더링 행렬이 지워졌다.
        if let Some(w) = json_u32(props_json, "width") {
            if w != pic.common.width {
                Self::apply_picture_display_width(pic, w);
            }
        }
        if let Some(h) = json_u32(props_json, "height") {
            if h != pic.common.height {
                Self::apply_picture_display_height(pic, h);
            }
        }

        // 위치 속성
        if let Some(tac) = json_bool(props_json, "treatAsChar") {
            pic.common.treat_as_char = tac;
            // attr 비트 갱신
            if tac {
                pic.common.attr |= 0x01;
            } else {
                pic.common.attr &= !0x01;
            }
        }
        if let Some(v) = json_str(props_json, "vertRelTo") {
            pic.common.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,
                _ => pic.common.vert_rel_to,
            };
        }
        if let Some(v) = json_str(props_json, "horzRelTo") {
            pic.common.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,
                _ => pic.common.horz_rel_to,
            };
        }
        if let Some(v) = json_str(props_json, "vertAlign") {
            pic.common.vert_align = match v.as_str() {
                "Top" => crate::model::shape::VertAlign::Top,
                "Center" => crate::model::shape::VertAlign::Center,
                "Bottom" => crate::model::shape::VertAlign::Bottom,
                _ => pic.common.vert_align,
            };
        }
        if let Some(v) = json_str(props_json, "horzAlign") {
            pic.common.horz_align = match v.as_str() {
                "Left" => crate::model::shape::HorzAlign::Left,
                "Center" => crate::model::shape::HorzAlign::Center,
                "Right" => crate::model::shape::HorzAlign::Right,
                _ => pic.common.horz_align,
            };
        }
        if let Some(v) = json_str(props_json, "textWrap") {
            pic.common.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,
                _ => pic.common.text_wrap,
            };
        }
        if let Some(v) = json_bool(props_json, "restrictInPage") {
            pic.common.flow_with_text = v;
            if v {
                pic.common.attr |= 1 << 13;
                pic.common.allow_overlap = false;
                pic.common.attr &= !(1 << 14);
            } else {
                pic.common.attr &= !(1 << 13);
            }
        }
        if let Some(v) = json_bool(props_json, "allowOverlap") {
            pic.common.allow_overlap = v;
            if v {
                pic.common.attr |= 1 << 14;
            } else {
                pic.common.attr &= !(1 << 14);
            }
        }
        if let Some(v) = json_bool(props_json, "sizeProtect") {
            pic.common.size_protect = v;
            if v {
                pic.common.attr |= 1 << 20;
            } else {
                pic.common.attr &= !(1 << 20);
            }
        }
        // [#6806] 「쪽 영역 안으로 제한」이 켜졌다는 이유로 「서로 겹침 허용」을 끄지
        // 않는다 — 한컴은 두 플래그를 **동시에 켜서 저장**한다(코퍼스: 그림 518 중 70,
        // 도형 894 중 12, 표 5428 중 39). 이 강제는 봉지에 무엇이 있든 돌아서, 게터가
        // 내보낸 `allowOverlap:true` 를 되먹이기만 해도 false 로 뒤집었다(get∘set 비항등).
        // 사용자가 실제로 「쪽 영역 제한」을 켜는 편집은 위 `restrictInPage` 갈래가
        // 종전대로 겹침을 끄므로 그 계약은 그대로다. 도형·수식이 쓰는 공용 경로
        // (`apply_common_obj_attr_from_json`)에는 이 강제가 이미 없다.
        if let Some(v) = json_i32(props_json, "vertOffset") {
            pic.common.vertical_offset = v as u32;
        }
        if let Some(v) = json_i32(props_json, "horzOffset") {
            pic.common.horizontal_offset = v as u32;
        }
        Self::sync_common_obj_attr_known_bits(&mut pic.common);

        // 이미지 속성
        if let Some(v) = json_i32(props_json, "brightness") {
            pic.image_attr.brightness = v as i8;
        }
        if let Some(v) = json_i32(props_json, "contrast") {
            pic.image_attr.contrast = v as i8;
        }
        if let Some(v) = json_i32(props_json, "transparency") {
            pic.image_attr.transparency = v.clamp(0, 100) as u8;
        }
        if let Some(v) = json_str(props_json, "effect") {
            pic.image_attr.effect = match v.as_str() {
                "GrayScale" => crate::model::image::ImageEffect::GrayScale,
                "BlackWhite" => crate::model::image::ImageEffect::BlackWhite,
                "Pattern8x8" => crate::model::image::ImageEffect::Pattern8x8,
                _ => crate::model::image::ImageEffect::RealPic,
            };
        }

        // 회전/대칭 — [#6806] "키 존재" 가 아니라 "값 변화" 가 회전 변경이다. 게터는 이 키를
        // 항상 내보내므로, 종전에는 같은 각도를 되먹여도 `refresh_picture_rotation_layout_for_save`
        // 가 돌아 `common` 을 `current` 로 다시 세웠다(#6355 지문 판정을 앞단에서 무력화).
        if let Some(v) = json_i16(props_json, "rotationAngle") {
            if v != pic.shape_attr.rotation_angle {
                pic.shape_attr.rotation_angle = v;
                rotation_changed = true;
            }
        }
        if let Some(v) = json_bool(props_json, "horzFlip") {
            pic.shape_attr.horz_flip = v;
            if v {
                pic.shape_attr.flip |= 0x01;
            } else {
                pic.shape_attr.flip &= !0x01;
            }
        }
        if let Some(v) = json_bool(props_json, "vertFlip") {
            pic.shape_attr.vert_flip = v;
            if v {
                pic.shape_attr.flip |= 0x02;
            } else {
                pic.shape_attr.flip &= !0x02;
            }
        }
        if rotation_changed {
            Self::refresh_picture_rotation_layout_for_save(pic);
        }

        // [#5890] 변환 파생 상태 무효화 — 실제로 변환이 바뀐 뒤에만 한다.
        // `refresh_picture_rotation_layout_for_save` 가 크기·위치를 다시 세우므로
        // 그 뒤에 지문을 비교한다. 변화가 없으면 한컴 원본 렌더링 행렬을 그대로 둔다
        // (직렬화기는 `raw_rendering` 이 비어 있을 때만 행렬을 새로 만든다 —
        // src/serializer/control.rs 의 rendering 블록).
        if Self::picture_transform_fingerprint(pic) != transform_before {
            pic.shape_attr.raw_rendering.clear();
            // 회전 없는 저장 경로는 이 명시적 행렬을 소비한다. 플래그만 바꾸면
            // 한컴은 반전 전 그림을 출력하므로 원본 사각형 안의 반전도 기록한다.
            let [sx, b, tx, c, sy, ty] = pic.shape_attr.local_reflection_matrix();
            pic.shape_attr.render_tx = pic.shape_attr.offset_x as f64 + tx;
            pic.shape_attr.render_ty = pic.shape_attr.offset_y as f64 + ty;
            pic.shape_attr.render_sx = sx;
            pic.shape_attr.render_sy = sy;
            pic.shape_attr.render_b = b;
            pic.shape_attr.render_c = c;
        }

        // 자르기: HWP 내부 crop은 원본 이미지의 source rect 좌표이고,
        // 속성 창 UI는 네 방향에서 잘라낸 양을 표시한다.
        let crop_left = json_i32(props_json, "cropLeft");
        let crop_top = json_i32(props_json, "cropTop");
        let crop_right = json_i32(props_json, "cropRight");
        let crop_bottom = json_i32(props_json, "cropBottom");
        if crop_left.is_some()
            || crop_top.is_some()
            || crop_right.is_some()
            || crop_bottom.is_some()
        {
            let (mut left, mut top, mut right, mut bottom) = Self::picture_crop_ui_amounts(pic);
            if let Some(v) = crop_left {
                left = v;
            }
            if let Some(v) = crop_top {
                top = v;
            }
            if let Some(v) = crop_right {
                right = v;
            }
            if let Some(v) = crop_bottom {
                bottom = v;
            }
            Self::set_picture_crop_from_ui_amounts(pic, left, top, right, bottom);
        }

        // 안쪽 여백 (그림 여백)
        if let Some(v) = json_i16(props_json, "paddingLeft") {
            pic.padding.left = v;
        }
        if let Some(v) = json_i16(props_json, "paddingTop") {
            pic.padding.top = v;
        }
        if let Some(v) = json_i16(props_json, "paddingRight") {
            pic.padding.right = v;
        }
        if let Some(v) = json_i16(props_json, "paddingBottom") {
            pic.padding.bottom = v;
        }

        // 바깥 여백
        if let Some(v) = json_i16(props_json, "outerMarginLeft") {
            pic.common.margin.left = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginTop") {
            pic.common.margin.top = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginRight") {
            pic.common.margin.right = v;
        }
        if let Some(v) = json_i16(props_json, "outerMarginBottom") {
            pic.common.margin.bottom = v;
        }

        // 테두리
        if let Some(v) = json_u32(props_json, "borderColor") {
            pic.border_color = v;
        }
        if let Some(v) = json_i32(props_json, "borderWidth") {
            pic.border_width = v;
        }

        // description
        if let Some(v) = json_str(props_json, "description") {
            pic.common.description = v;
        }

        let mut caption_created = false;

        // 캡션
        if let Some(has_cap) = json_bool(props_json, "hasCaption") {
            if has_cap {
                // 캡션이 없으면 새로 생성 (기본 문단 포함)
                if pic.caption.is_none() {
                    let mut cap = crate::model::shape::Caption::default();
                    // AutoNumber 컨트롤 생성 (번호 할당은 아래에서)
                    let an = crate::model::control::AutoNumber {
                        number_type: crate::model::control::AutoNumberType::Picture,
                        ..Default::default()
                    };
                    cap.paragraphs.push(
                        crate::model::paragraph::Paragraph::new_auto_number_caption("그림 ", an),
                    );
                    // 캡션 텍스트 최대 폭 = 개체 폭
                    cap.max_width = pic.common.width;
                    pic.caption = Some(cap);
                    caption_created = true;
                    // attr bit 29: 캡션 존재 플래그 (한컴 호환성)
                    pic.common.attr |= 1 << 29;
                }
                let cap = pic.caption.as_mut().unwrap();
                if let Some(v) = json_str(props_json, "captionDirection") {
                    cap.direction = match v.as_str() {
                        "Left" => crate::model::shape::CaptionDirection::Left,
                        "Right" => crate::model::shape::CaptionDirection::Right,
                        "Top" => crate::model::shape::CaptionDirection::Top,
                        _ => crate::model::shape::CaptionDirection::Bottom,
                    };
                }
                if let Some(v) = json_str(props_json, "captionVertAlign") {
                    cap.vert_align = match v.as_str() {
                        "Center" => crate::model::shape::CaptionVertAlign::Center,
                        "Bottom" => crate::model::shape::CaptionVertAlign::Bottom,
                        _ => crate::model::shape::CaptionVertAlign::Top,
                    };
                }
                if let Some(v) = json_u32(props_json, "captionWidth") {
                    cap.width = v;
                }
                if let Some(v) = json_i16(props_json, "captionSpacing") {
                    cap.spacing = v;
                }
                if let Some(v) = json_bool(props_json, "captionIncludeMargin") {
                    cap.include_margin = v;
                }
            } else {
                pic.caption = None;
                pic.common.attr &= !(1 << 29);
            }
        }

        caption_created
    }
    /// 띄운 그림(글자처럼 취급 아님)을 다른 문단·셀 문단으로 옮겨 붙이고 위치를 새로 정한다.
    ///
    /// 개체를 끌어 다른 쪽에 놓으면 한컴은 개체의 조판 부호(앵커)를 놓은 자리의 문단으로
    /// 옮긴다. 앵커가 원래 쪽에 남으면 개체는 원래 쪽 기준으로 그려져 쪽 밖으로 잘린다.
    /// 그림 데이터(BinData)는 그대로 두고 컨트롤만 옮긴다. 셀 경로가 비면 본문 문단이다.
    /// 오프셋은 그림의 기존 위치 기준(가로·세로)에 대한 HWPUNIT 값이다. 표 칸 문단으로 옮기면
    /// 기준을 세로 문단·가로 단으로 바꾸고 본문 영역 제한을 켠다(한컴 칸 그림 저장 형태). 이때
    /// 오프셋은 그 칸 문단 기준으로 해석되므로, 호출자는 옮긴 뒤 실제 배치와의 차이를 보정한다.
    #[allow(clippy::too_many_arguments)]
    pub fn relocate_floating_picture_native(
        &mut self,
        src_section: usize,
        src_para: usize,
        src_cell_path: &[(usize, usize, usize)],
        src_control: usize,
        dst_section: usize,
        dst_para: usize,
        dst_char_offset: usize,
        dst_cell_path: &[(usize, usize, usize)],
        horz_offset: i32,
        vert_offset: i32,
    ) -> Result<String, HwpError> {
        if dst_section >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과",
                dst_section
            )));
        }
        // 옮기기 전에 도착 문단이 있는지 확인해, 실패하면 문서를 바꾸지 않는다.
        Self::resolve_cell_paragraph_mut(
            &mut self.document.sections[dst_section],
            dst_para,
            dst_cell_path,
        )?;
        // 도착 컨테이너의 종류도 제거 전에 검증한다. 그림 캡션 등 지원하지 않는
        // 경로를 나중에 거절하면 원본 그림만 먼저 사라질 수 있다.
        let into_table_cell = !dst_cell_path.is_empty()
            && !Self::cell_path_terminates_at_textbox(
                &self.document.sections[dst_section],
                dst_para,
                dst_cell_path,
            )?;
        let picture = {
            let section = self.document.sections.get_mut(src_section).ok_or_else(|| {
                HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", src_section))
            })?;
            let para = Self::resolve_cell_paragraph_mut(section, src_para, src_cell_path)?;
            match para.controls.get(src_control) {
                Some(Control::Picture(pic)) if !pic.common.treat_as_char => {}
                Some(Control::Picture(_)) => {
                    return Err(HwpError::RenderError(
                        "글자처럼 취급하는 그림은 옮겨 붙일 수 없습니다".to_string(),
                    ))
                }
                _ => {
                    return Err(HwpError::RenderError(
                        "지정된 컨트롤이 그림이 아닙니다".to_string(),
                    ))
                }
            }
            let removed = para.remove_control(src_control);
            Self::reflow_paragraph_line_segs_after_control_delete(para, &self.styles, self.dpi);
            section.raw_stream = None;
            removed
        };
        if src_cell_path.is_empty() {
            if let Some(active) = self.active_field.as_mut() {
                if active.section_idx == src_section
                    && active.para_idx == src_para
                    && active.cell_path.is_none()
                    && active.control_idx > src_control
                {
                    active.control_idx -= 1;
                }
            }
        }
        let dst_path = if dst_section == src_section && dst_para == src_para {
            Self::path_after_control_removal(src_cell_path, src_control, dst_cell_path)
        } else {
            dst_cell_path.to_vec()
        };
        let mut picture = picture;
        if let Control::Picture(pic) = &mut picture {
            pic.common.horizontal_offset = horz_offset as u32;
            pic.common.vertical_offset = vert_offset as u32;
            if into_table_cell {
                // 표 칸 문단 안 그림은 한컴 저장본처럼 세로 문단·가로 단 기준에 본문 영역 제한(bit 13)을
                // 켠다. 종이 기준이나 제한 없음이면 한컴은 칸이 아니라 바깥 문단·종이 기준으로 그린다.
                let common = &mut pic.common;
                common.vert_rel_to = crate::model::shape::VertRelTo::Para;
                common.horz_rel_to = crate::model::shape::HorzRelTo::Column;
                common.flow_with_text = true;
                common.attr =
                    (common.attr & !((0x3 << 3) | (0x3 << 8))) | (2 << 3) | (2 << 8) | (1 << 13);
            }
        }
        let new_ctrl_idx = {
            let section = &mut self.document.sections[dst_section];
            section.raw_stream = None;
            let target = Self::resolve_cell_paragraph_mut(section, dst_para, &dst_path)?;
            let new_ctrl_idx = Self::control_insert_index(target, dst_char_offset);
            target.align_ctrl_data_records();
            target.controls.insert(new_ctrl_idx, picture);
            target.ctrl_data_records.insert(new_ctrl_idx, None);
            target.shift_for_inline_control_insert(new_ctrl_idx, dst_char_offset);
            target.control_mask |= 0x00000800;
            new_ctrl_idx
        };
        if let Some(&(table_idx, _, _)) = src_cell_path.first() {
            self.mark_cell_control_dirty(src_section, src_para, table_idx);
        }
        if let Some(&(table_idx, _, _)) = dst_path.first() {
            self.mark_cell_control_dirty(dst_section, dst_para, table_idx);
        }
        for section_idx in [src_section, dst_section] {
            self.mark_section_dirty(section_idx);
            self.recompose_section(section_idx);
        }
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();
        self.event_log.push(DocumentEvent::PictureDeleted {
            section: src_section,
            para: src_para,
            ctrl: src_control,
        });
        self.event_log.push(DocumentEvent::PictureInserted {
            section: dst_section,
            para: dst_para,
        });
        // 소비자는 삭제 전 hit-test 경로를 재사용하지 않고 실제 도착 소유 경로를 쓴다.
        let cell_path: Vec<_> = dst_path
            .iter()
            .map(|&(control, cell, para)| {
                serde_json::json!({
                    "controlIndex": control, "cellIndex": cell, "cellParaIndex": para
                })
            })
            .collect();
        Ok(serde_json::json!({
            "ok": true, "sec": dst_section, "paraIdx": dst_para,
            "controlIdx": new_ctrl_idx, "cellPath": cell_path
        })
        .to_string())
    }

    /// 같은 본문 문단 아래에서 `src_path` 문단의 `removed` 번 컨트롤이 빠진 뒤의 `dst_path`.
    /// 도착 경로가 그 문단의 뒤쪽 컨트롤(표)을 거치면 번호가 하나 당겨진다.
    fn path_after_control_removal(
        src_path: &[(usize, usize, usize)],
        removed: usize,
        dst_path: &[(usize, usize, usize)],
    ) -> Vec<(usize, usize, usize)> {
        let mut path = dst_path.to_vec();
        let depth = src_path.len();
        if path.len() > depth && path[..depth] == *src_path && path[depth].0 > removed {
            path[depth].0 -= 1;
        }
        path
    }

    /// 그림 컨트롤을 문단에서 삭제한다 (네이티브).
    pub fn delete_picture_control_native(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과",
                section_idx
            )));
        }
        let section = &mut self.document.sections[section_idx];
        if parent_para_idx >= section.paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "부모 문단 인덱스 {} 범위 초과",
                parent_para_idx
            )));
        }
        let para = &mut section.paragraphs[parent_para_idx];
        if control_idx >= para.controls.len() {
            return Err(HwpError::RenderError(format!(
                "컨트롤 인덱스 {} 범위 초과",
                control_idx
            )));
        }
        // 그림 컨트롤인지 확인
        if !matches!(
            &para.controls[control_idx],
            crate::model::control::Control::Picture(_)
        ) {
            return Err(HwpError::RenderError(
                "지정된 컨트롤이 그림이 아닙니다".to_string(),
            ));
        }

        para.remove_control(control_idx);
        // 컨트롤 배열이 줄어도 활성 누름틀은 같은 필드를 가리켜야 한다.
        if let Some(active) = self.active_field.as_mut() {
            if active.section_idx == section_idx
                && active.para_idx == parent_para_idx
                && active.cell_path.is_none()
                && active.control_idx > control_idx
            {
                active.control_idx -= 1;
            }
        }

        // line_segs 재계산: 그림 높이가 반영된 line_segs를 텍스트 기반으로 리셋
        Self::reflow_paragraph_line_segs_after_control_delete(para, &self.styles, self.dpi);

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

        self.event_log.push(DocumentEvent::PictureDeleted {
            section: section_idx,
            para: parent_para_idx,
            ctrl: control_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }
    /// [Task #2230] 임베디드 BinData 등록 (콘텐츠 + 메타데이터) — 반환값은
    /// bin_data_id(위치, 1-based 순번).
    ///
    /// bin_data_id 와 storage id(BIN%04X 스트림 이름)는 다른 의미다. 위치는
    /// 배열 순번으로 유지하고, storage id 는 기존 id 와 충돌하지 않게
    /// 최댓값+1 로 채번한다 — 순번 채번은 storage id 에 구멍이 있는 문서에서
    /// 기존 이미지와 스트림 이름이 충돌해 저장 시 이미지가 뒤바뀌거나
    /// 소실된다. (insert_picture_native 와 그림 지정이 규칙 공유.)
    pub(crate) fn register_embedded_bin_data(&mut self, image_data: &[u8], extension: &str) -> u16 {
        crate::model::bin_data::register_embedded_bin_data(
            &mut self.document,
            image_data,
            extension,
        )
    }

    /// [Task #2230] 기존 Picture 컨트롤에 이미지를 지정한다 — 그림 미지정
    /// placeholder(bin 참조 실패 + 외부 경로 없음)의 편집 뷰 그림 삽입.
    ///
    /// - BinData 등록 규칙은 insert_picture_native 와 공유
    ///   (register_embedded_bin_data).
    /// - 개체 틀 크기(common.width/height)와 배치 속성은 유지한다 — 한컴
    ///   placeholder 는 틀에 그림을 맞추므로 레이아웃 불변.
    /// - crop 은 insert_picture_native 와 동일하게 원본 전체
    ///   (natural px × 75 = HWPUNIT@96dpi) 로 설정한다.
    /// - `cell_path` 가 비어있으면 본문/각주 문단의 컨트롤, 있으면 셀/글상자
    ///   안 문단의 컨트롤을 대상으로 한다.
    pub fn assign_picture_image_native(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        cell_path: &[(usize, usize, usize)],
        control_idx: usize,
        image_data: &[u8],
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
    ) -> Result<String, HwpError> {
        if image_data.is_empty() {
            return Err(HwpError::RenderError(
                "이미지 데이터가 비어 있습니다".to_string(),
            ));
        }
        // 대상 존재 검증을 BinData 등록보다 먼저 수행 — 실패 시 문서 무변형.
        if cell_path.is_empty() {
            self.resolve_picture_control_ref(section_idx, parent_para_idx, control_idx)?;
        } else {
            let para = self.resolve_paragraph_by_path(section_idx, parent_para_idx, cell_path)?;
            let ctrl = para.controls.get(control_idx).ok_or_else(|| {
                HwpError::RenderError(format!("셀 내 컨트롤 {} 범위 초과", control_idx))
            })?;
            if !matches!(ctrl, Control::Picture(_)) {
                return Err(HwpError::RenderError(
                    "지정된 셀 내 컨트롤이 그림이 아닙니다".to_string(),
                ));
            }
        }

        let position_id = self.register_embedded_bin_data(image_data, extension);

        {
            let pic = if cell_path.is_empty() {
                self.resolve_picture_control_mut(section_idx, parent_para_idx, control_idx)?
            } else {
                let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
                    HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
                })?;
                let para = Self::resolve_cell_paragraph_mut(section, parent_para_idx, cell_path)?;
                let ctrl = para.controls.get_mut(control_idx).ok_or_else(|| {
                    HwpError::RenderError(format!("셀 내 컨트롤 {} 범위 초과", control_idx))
                })?;
                match ctrl {
                    Control::Picture(p) => p,
                    _ => {
                        return Err(HwpError::RenderError(
                            "지정된 셀 내 컨트롤이 그림이 아닙니다".to_string(),
                        ))
                    }
                }
            };
            pic.image_attr.bin_data_id = position_id;
            pic.image_attr.external_path = None;
            pic.crop = crate::model::image::CropInfo {
                left: 0,
                top: 0,
                right: (natural_width_px * 75) as i32,
                bottom: (natural_height_px * 75) as i32,
            };
        }

        let section = &mut self.document.sections[section_idx];
        section.raw_stream = None;
        self.recompose_section(section_idx);
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();
        self.event_log.push(DocumentEvent::PictureResized {
            section: section_idx,
            para: parent_para_idx,
            ctrl: control_idx,
        });
        Ok(format!("{{\"ok\":true,\"binDataId\":{}}}", position_id))
    }

    /// 커서 위치에 그림을 삽입한다 (네이티브).
    ///
    /// - `cell_path` 가 비어있으면 본문 paragraph 에 inline (treat_as_char=true) 삽입.
    /// - `cell_path` 가 있으면 표 셀 영역에 floating picture (tac=false, wrap=Square,
    ///   Page-relative offset) 로 삽입한다. 셀 자체는 비어있는 채로 유지되어 cursor
    ///   클릭이 정상 동작 (#1151). 한컴 2022 의 셀 이미지 삽입 패턴과 동일
    ///   (incellpicture.hwp 검증).
    ///
    /// `paper_offset_x_hu / paper_offset_y_hu`: 셀 floating 분기에서 사용할 paper-relative
    /// 좌표 (HWPUNIT). `None` 이면 셀 좌상단 (`compute_cell_page_offset`) 을 default 로 사용
    /// — 기존 동작 + API caller 호환. studio drag 좌표 기반 호출은 `Some` 으로 전달.
    /// 본문 inline 분기 (cell_path 비어있음) 는 본 매개변수를 사용하지 않는다.
    #[allow(clippy::too_many_arguments)]
    /// [#4347] 확장 컨트롤이 끼어들 `controls` 자리 — **글자 차례**를 따른다.
    ///
    /// 끝에 붙이면 자리표가 뒤죽박죽이 된다. 새 번호·수식·각주 경로가 쓰는 규약과 같다.
    fn control_insert_index(
        paragraph: &crate::model::paragraph::Paragraph,
        char_offset: usize,
    ) -> usize {
        let positions = crate::document_core::helpers::find_control_text_positions(paragraph);
        positions
            .iter()
            .position(|&pos| pos > char_offset)
            .unwrap_or(paragraph.controls.len())
    }

    /// [#4347] 넣은 컨트롤이 **스트림에서 차지한 8칸**을 문단 좌표에 남긴다.
    ///
    /// 파서는 확장 컨트롤에 보이는 글자를 안 남기므로, 그 컨트롤의 자리는
    /// `control_text_positions()` 가 `char_offsets` 의 **갭**으로 되짚는다. 삽입이 그 갭을
    /// 안 만들면 컨트롤이 자리를 잃고 문단 끝 폴백으로 떨어진다 — 그림 앵커가 20 대신 406
    /// 이던 것이 그 탓이다. 수식·각주 경로가 이미 이 꼴이다.
    fn leave_coordinate_trace(
        paragraph: &mut crate::model::paragraph::Paragraph,
        control_idx: usize,
        char_offset: usize,
    ) {
        paragraph.shift_for_inline_control_insert(control_idx, char_offset);
        paragraph.char_count += 8;
    }

    pub fn insert_picture_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        cell_path: &[(usize, usize, usize)],
        image_data: &[u8],
        width: u32,
        height: u32,
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
        description: &str,
        paper_offset_x_hu: Option<i32>,
        paper_offset_y_hu: Option<i32>,
    ) -> Result<String, HwpError> {
        self.insert_picture_native_anchored(
            section_idx,
            para_idx,
            char_offset,
            cell_path,
            image_data,
            width,
            height,
            natural_width_px,
            natural_height_px,
            extension,
            description,
            paper_offset_x_hu,
            paper_offset_y_hu,
            false,
        )
    }

    /// 표 셀 경로의 그림을 **그 셀 문단 안**에 넣는다 (`cell_path` 필수).
    ///
    /// [`Self::insert_picture_native`] 의 셀 분기는 그림을 표를 가진 본문 문단에 띄운다(#1151).
    /// 한컴에서 셀 안 커서로 서명·도장을 넣고 저장한 문서는 그림을 셀 문단의 컨트롤로 담는다
    /// (가로 기준 단, 세로 기준 문단). 그렇게 넣어야 행 높이·표 이동·쪽 나눔에서 그림이 셀과
    /// 함께 움직인다. 오프셋은 단·문단 기준(HWPUNIT, 음수 허용)이며 `None` 이면 0 이다.
    #[allow(clippy::too_many_arguments)]
    pub fn insert_picture_in_cell_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        cell_path: &[(usize, usize, usize)],
        image_data: &[u8],
        width: u32,
        height: u32,
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
        description: &str,
        offset_x_hu: Option<i32>,
        offset_y_hu: Option<i32>,
    ) -> Result<String, HwpError> {
        if cell_path.is_empty() {
            return Err(HwpError::RenderError(
                "셀 안 그림 넣기에는 셀 경로가 필요합니다".to_string(),
            ));
        }
        self.insert_picture_native_anchored(
            section_idx,
            para_idx,
            char_offset,
            cell_path,
            image_data,
            width,
            height,
            natural_width_px,
            natural_height_px,
            extension,
            description,
            offset_x_hu,
            offset_y_hu,
            true,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn insert_picture_native_anchored(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        cell_path: &[(usize, usize, usize)],
        image_data: &[u8],
        width: u32,
        height: u32,
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
        description: &str,
        paper_offset_x_hu: Option<i32>,
        paper_offset_y_hu: Option<i32>,
        anchor_in_cell: bool,
    ) -> Result<String, HwpError> {
        use crate::model::image::Picture;
        use crate::model::paragraph::{CharShapeRef, LineSeg};
        use crate::model::shape::{CommonObjAttr, HorzRelTo, VertRelTo};
        // 유효성 검사
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과 (총 {}개)",
                section_idx,
                self.document.sections.len()
            )));
        }
        if para_idx >= self.document.sections[section_idx].paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "문단 인덱스 {} 범위 초과",
                para_idx
            )));
        }
        if image_data.is_empty() {
            return Err(HwpError::RenderError(
                "이미지 데이터가 비어 있습니다".to_string(),
            ));
        }
        // cell_path 가 있으면 경로가 유효한지 사전 검증한다.
        //
        // 표 셀 picture 는 한컴 정합상 표 sibling floating 으로 삽입하지만,
        // 글상자(text_box) 내부 picture 는 글상자 문단의 control 로 들어가야 한다.
        // 기존 resolve_cell_by_path 는 마지막 엔트리가 표일 때만 성공하므로
        // 먼저 표/글상자를 구분한다.
        let cell_path_is_textbox = if !cell_path.is_empty() {
            let section = &self.document.sections[section_idx];
            let is_textbox = Self::cell_path_terminates_at_textbox(section, para_idx, cell_path)?;
            if !is_textbox {
                self.resolve_cell_by_path(section_idx, para_idx, cell_path)?;
            }
            is_textbox
        } else {
            false
        };

        // 셀 자체가 있어도 마지막 문단 번호는 잘못될 수 있다. BinData 등록 전에
        // 실제 삽입 문단까지 검증해 실패한 요청이 문서 자원을 남기지 않게 한다.
        if cell_path_is_textbox || anchor_in_cell {
            self.resolve_paragraph_by_path(section_idx, para_idx, cell_path)?;
        }

        // --- 1·2. BinData 등록 (콘텐츠 + 메타데이터) ---
        // [Task #2230] 그림 지정(assign_picture_image_native)과 규칙 공유를 위해
        // register_embedded_bin_data 로 추출.
        let position_id = self.register_embedded_bin_data(image_data, extension);

        if !cell_path.is_empty() {
            if cell_path_is_textbox || anchor_in_cell {
                // === 글상자 내부 picture 분기 (#1322 maintainer fix) ===
                // (`insert_picture_in_cell_native` 의 표 셀 문단 삽입도 이 분기를 쓴다.)
                // hitTest 의 글상자 sentinel path (`cellIdx=0`) 가 넘어온 경우에는
                // Picture 를 body paragraph 의 sibling 으로 띄우지 않고, 실제 text_box
                // paragraph 안에 삽입한다. 글상자 내부 좌표계는 text_box content box
                // 기준이므로 caller 가 전달한 offset 은 Para-relative 로 해석한다.
                let offset_x_hu = paper_offset_x_hu.unwrap_or(0);
                let offset_y_hu = paper_offset_y_hu.unwrap_or(0);
                // 표 셀 문단 안 그림은 한컴 저장본처럼 가로 기준을 단(셀 내용 영역)으로 둔다.
                let (horz_rel_to, horz_rel_bits) = if cell_path_is_textbox {
                    (HorzRelTo::Para, 3u32)
                } else {
                    (HorzRelTo::Column, 2u32)
                };

                // CommonObjAttr (text_box 내부 floating):
                //   bits 3-4=vert_rel_to(2=Para), bits 8-10=horz_rel_to(3=Para),
                //   bits 15-17=width_criterion(4=Absolute),
                //   bits 18-20=height_criterion(2=Absolute),
                //   bits 21-23=text_wrap(0=Square)
                // 표 셀 문단 안 그림은 한컴처럼 본문 영역 제한(bit 13)을 켠다. 꺼 두면 한컴은
                // 셀이 아니라 표를 둔 바깥 문단 기준으로 위치를 잡아 셀 밖(표 머리)에 그린다.
                let in_table_cell = !cell_path_is_textbox;
                let common_attr: u32 = (2 << 3)
                    | (horz_rel_bits << 8)
                    | ((in_table_cell as u32) << 13)
                    | (4 << 15)
                    | (2 << 18)
                    | (1 << 26);
                let common = CommonObjAttr {
                    ctrl_id: 0x67736F20,
                    attr: common_attr,
                    numbering_type: crate::model::shape::ObjectNumberingType::Picture,
                    treat_as_char: false,
                    vert_rel_to: VertRelTo::Para,
                    horz_rel_to,
                    text_wrap: crate::model::shape::TextWrap::Square,
                    flow_with_text: in_table_cell,
                    horizontal_offset: if cell_path_is_textbox {
                        offset_x_hu.max(0)
                    } else {
                        offset_x_hu
                    } as u32,
                    vertical_offset: if cell_path_is_textbox {
                        offset_y_hu.max(0)
                    } else {
                        offset_y_hu
                    } as u32,
                    width,
                    height,
                    z_order: 1,
                    description: description.to_string(),
                    ..Default::default()
                };
                let pic = Picture::from_embedded_image(
                    common,
                    position_id,
                    natural_width_px,
                    natural_height_px,
                );

                let (new_ctrl_idx, logical_after) = {
                    let section = &mut self.document.sections[section_idx];
                    section.raw_stream = None;
                    let target_para =
                        Self::resolve_cell_paragraph_mut(section, para_idx, cell_path)?;
                    // [#4347] **글상자 문단은 글자를 담는다.** 표 문단(글자 없음)과 달리 여기서는
                    // 갭이 없으면 자리가 어긋난다 — 글자 일곱 개짜리 글상자의 자리 3 에 그림을
                    // 넣어도 스트림 대응이 그대로였고(4→4), 캐럿이 설 수 있는 첫 자리가 0 에서
                    // 7 로 튀었다. 본문 문단과 같은 자취를 남긴다.
                    let new_ctrl_idx = Self::control_insert_index(target_para, char_offset);
                    target_para.align_ctrl_data_records();
                    target_para
                        .controls
                        .insert(new_ctrl_idx, Control::Picture(Box::new(pic)));
                    target_para.ctrl_data_records.insert(new_ctrl_idx, None);
                    target_para.shift_for_inline_control_insert(new_ctrl_idx, char_offset);
                    target_para.control_mask |= 0x00000800;
                    let logical_positions =
                        crate::document_core::helpers::find_logical_control_positions(target_para);
                    let logical_after = logical_positions
                        .get(new_ctrl_idx)
                        .copied()
                        .unwrap_or_else(|| target_para.text.chars().count())
                        + 1;
                    (new_ctrl_idx, logical_after)
                };

                if !cell_path_is_textbox {
                    // 셀 문단이 바뀌었으므로 최외곽 표 host 문단의 측정 revision도 무효화한다.
                    self.mark_cell_control_dirty(section_idx, para_idx, cell_path[0].0);
                }
                self.mark_section_dirty(section_idx);
                self.recompose_section(section_idx);
                self.paginate_if_needed();
                self.invalidate_page_tree_cache();

                self.event_log.push(DocumentEvent::PictureInserted {
                    section: section_idx,
                    para: para_idx,
                });
                return Ok(crate::document_core::helpers::json_ok_with(&format!(
                    "\"paraIdx\":{},\"controlIdx\":{},\"logicalOffset\":{}",
                    para_idx, new_ctrl_idx, logical_after
                )));
            }

            // === 셀 floating picture 분기 (#1151 v2 — 한컴 패턴 정합) ===
            // Picture 는 표가 들어있는 paragraph 의 sibling control 로 append 된다.
            // tac=false, wrap=Square (어울림), horz/vert_rel_to=Paper, offset 은 사용자 클릭/드래그 위치.
            // [Task #1151 v8] 결함 A fix: 한컴 native default 가 Paper (incellpicture.hwp dump
            // 확인 — horz_rel_to=Paper offset=11845, vert_rel_to=Paper offset=15595).
            // [Task #1151 v8] 결함 C fix: 사용자가 클릭/드래그한 좌표 (paper-relative HU) 사용 —
            // 한컴 native 동작 정합. caller (studio) 가 None 전달 시 셀 좌상단 default.
            let (offset_x_hu, offset_y_hu) = match (paper_offset_x_hu, paper_offset_y_hu) {
                (Some(x), Some(y)) => (x, y),
                _ => self.compute_cell_page_offset(section_idx, para_idx, cell_path),
            };

            // CommonObjAttr (floating):
            //   bits 3-4=vert_rel_to(0=Paper), bits 8-10=horz_rel_to(0=Paper),
            //   bits 15-17=width_criterion(4=Absolute), bits 18-20=height_criterion(2=Absolute),
            //   bits 21-23=text_wrap(0=Square)
            let common_attr: u32 = (4 << 15) | (2 << 18) | (1 << 26);
            let common = CommonObjAttr {
                ctrl_id: 0x67736F20,
                attr: common_attr,
                numbering_type: crate::model::shape::ObjectNumberingType::Picture,
                treat_as_char: false,
                vert_rel_to: VertRelTo::Paper,
                horz_rel_to: HorzRelTo::Paper,
                text_wrap: crate::model::shape::TextWrap::Square,
                horizontal_offset: offset_x_hu.max(0) as u32,
                vertical_offset: offset_y_hu.max(0) as u32,
                width,
                height,
                z_order: 1,
                description: description.to_string(),
                ..Default::default()
            };
            let pic = Picture::from_embedded_image(
                common,
                position_id,
                natural_width_px,
                natural_height_px,
            );

            // table 같은 paragraph 의 sibling control 로 append.
            //
            // [#4347] 이 경로는 **글자 없는 표 문단**에 붙는 자리라 좌표 자취가 필요 없다 —
            // 폴백 셈(`ci × 8`)이 곧 정답이다(실측 `표@0 그림@8`). 그런데도 길이를 더하면
            // 표 배치가 흔들린다(글자처럼 그림 둘의 줄 넘김 테스트가 깨진다). 건드리지 않는다.
            self.document.sections[section_idx].raw_stream = None;
            let parent = &mut self.document.sections[section_idx].paragraphs[para_idx];
            let new_ctrl_idx = parent.controls.len();
            parent.controls.push(Control::Picture(Box::new(pic)));
            parent.ctrl_data_records.push(None);
            let logical_positions =
                crate::document_core::helpers::find_logical_control_positions(parent);
            let logical_after = logical_positions
                .get(new_ctrl_idx)
                .copied()
                .unwrap_or_else(|| parent.text.chars().count())
                + 1;

            // 최외곽 표 host 문단의 측정 revision을 무효화한다.
            let outer_ctrl = cell_path[0].0;
            self.mark_cell_control_dirty(section_idx, para_idx, outer_ctrl);
            self.mark_section_dirty(section_idx);
            self.paginate_if_needed();
            // [Task #1151 v9 결함 F] page tree cache invalidate — v5 와 동일 결함 (다른
            // setter 들은 모두 호출하나 본 insert path 의 셀 분기만 누락). 두 picture
            // 연속 insert + toggle 시 cache stale → studio 화면 불일치.
            self.invalidate_page_tree_cache();

            self.event_log.push(DocumentEvent::PictureInserted {
                section: section_idx,
                para: para_idx,
            });
            return Ok(crate::document_core::helpers::json_ok_with(&format!(
                "\"paraIdx\":{},\"controlIdx\":{},\"logicalOffset\":{}",
                para_idx, new_ctrl_idx, logical_after
            )));
        }

        // === 본문 floating picture 분기 (Task #1151 v9 결함 E — 셀 분기와 동일 패턴) ===
        //
        // 한컴 native 동작 (사용자 시연 2026-05-30): 본문 picture 신규 삽입 시
        // 글자처럼 취급 default = **미체크** (tac=false, floating). 셀 안 picture
        // 와 동일. 이전 rhwp 본문 path 는 새 paragraph 생성 + inline glyph (tac=true)
        // 로 만들어 한컴 default 와 불일치 — 재설계하여 셀 분기와 통합.
        let (offset_x_hu, offset_y_hu) = match (paper_offset_x_hu, paper_offset_y_hu) {
            (Some(x), Some(y)) => (x, y),
            _ => (0, 0),
        };

        // CommonObjAttr (floating, 셀 분기와 동일):
        //   bits 3-4=vert_rel_to(0=Paper), bits 8-10=horz_rel_to(0=Paper),
        //   bits 15-17=width_criterion(4=Absolute), bits 18-20=height_criterion(2=Absolute),
        //   bits 21-23=text_wrap(0=Square)
        let common_attr: u32 = (4 << 15) | (2 << 18) | (1 << 26);
        let common = CommonObjAttr {
            ctrl_id: 0x67736F20, // "gso " — GenShape
            attr: common_attr,
            numbering_type: crate::model::shape::ObjectNumberingType::Picture,
            treat_as_char: false,
            vert_rel_to: VertRelTo::Paper,
            horz_rel_to: HorzRelTo::Paper,
            text_wrap: crate::model::shape::TextWrap::Square,
            horizontal_offset: offset_x_hu.max(0) as u32,
            vertical_offset: offset_y_hu.max(0) as u32,
            width,
            height,
            z_order: 1,
            description: description.to_string(),
            ..Default::default()
        };

        let pic =
            Picture::from_embedded_image(common, position_id, natural_width_px, natural_height_px);

        // 현재 paragraph 의 sibling control 로 끼운다 (새 paragraph 생성 X).
        self.document.sections[section_idx].raw_stream = None;
        let parent = &mut self.document.sections[section_idx].paragraphs[para_idx];
        let new_ctrl_idx = Self::control_insert_index(parent, char_offset);
        parent.align_ctrl_data_records();
        parent
            .controls
            .insert(new_ctrl_idx, Control::Picture(Box::new(pic)));
        parent.ctrl_data_records.insert(new_ctrl_idx, None);
        Self::leave_coordinate_trace(parent, new_ctrl_idx, char_offset);
        let logical_positions =
            crate::document_core::helpers::find_logical_control_positions(parent);
        let logical_after = logical_positions
            .get(new_ctrl_idx)
            .copied()
            .unwrap_or_else(|| parent.text.chars().count())
            + 1;
        self.shift_active_field_for_control_insert(section_idx, para_idx, new_ctrl_idx);

        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();
        // [Task #1151 v9 결함 F] page tree cache invalidate (v5 패턴).
        self.invalidate_page_tree_cache();

        self.event_log.push(DocumentEvent::PictureInserted {
            section: section_idx,
            para: para_idx,
        });
        Ok(crate::document_core::helpers::json_ok_with(&format!(
            "\"paraIdx\":{},\"controlIdx\":{},\"logicalOffset\":{}",
            para_idx, new_ctrl_idx, logical_after
        )))
    }
}

#[cfg(test)]
mod issue_1151_cell_picture_insert_tests {
    //! Issue #1151: 표 셀 안 이미지 삽입이 항상 표 밖 본문 문단에 들어가는 결함.
    //!
    //! v2 설계 — 한컴 정합 floating picture 접근:
    //! 셀 안 삽입 (cell_path 비어있지 않음) 시 picture 는 셀 내부 paragraph 에
    //! inline 삽입되지 않고, 표가 있는 같은 paragraph 의 sibling control 로
    //! floating (tac=false) 삽입된다. 셀 자체는 비어있는 채로 유지되어 사용자가
    //! 클릭으로 cursor 를 셀에 위치시킬 수 있다.

    use super::*;
    use crate::model::document::{Document, Section, SectionDef};
    use crate::model::page::PageDef;

    fn make_test_core() -> DocumentCore {
        let mut doc = Document::default();
        doc.sections.push(Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 59528,
                    height: 84188,
                    margin_left: 8504,
                    margin_right: 8504,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            paragraphs: vec![Paragraph::default()],
            trailing_lists: None,
            raw_stream: None,
            raw_provenance: None,
        });
        let mut core = DocumentCore::new_empty();
        core.set_document(doc);
        core
    }

    fn minimal_png() -> Vec<u8> {
        vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x00, 0x00, 0x00,
            0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ]
    }

    fn collect_picture_transparencies(doc: &Document) -> Vec<u8> {
        let mut values = Vec::new();
        for section in &doc.sections {
            collect_picture_transparencies_from_paragraphs(&section.paragraphs, &mut values);
        }
        values
    }

    fn collect_picture_transparencies_from_paragraphs(
        paragraphs: &[Paragraph],
        values: &mut Vec<u8>,
    ) {
        for para in paragraphs {
            for control in &para.controls {
                collect_picture_transparencies_from_control(control, values);
            }
        }
    }

    fn collect_picture_transparencies_from_control(control: &Control, values: &mut Vec<u8>) {
        match control {
            Control::Picture(pic) => {
                values.push(pic.image_attr.clamped_transparency());
                if let Some(caption) = &pic.caption {
                    collect_picture_transparencies_from_paragraphs(&caption.paragraphs, values);
                }
            }
            Control::Table(table) => {
                for cell in &table.cells {
                    collect_picture_transparencies_from_paragraphs(&cell.paragraphs, values);
                }
            }
            Control::Shape(shape) => collect_picture_transparencies_from_shape(shape, values),
            Control::Header(header) => {
                collect_picture_transparencies_from_paragraphs(&header.paragraphs, values);
            }
            Control::Footer(footer) => {
                collect_picture_transparencies_from_paragraphs(&footer.paragraphs, values);
            }
            Control::Footnote(footnote) => {
                collect_picture_transparencies_from_paragraphs(&footnote.paragraphs, values);
            }
            Control::Endnote(endnote) => {
                collect_picture_transparencies_from_paragraphs(&endnote.paragraphs, values);
            }
            _ => {}
        }
    }

    fn collect_picture_transparencies_from_shape(
        shape: &crate::model::shape::ShapeObject,
        values: &mut Vec<u8>,
    ) {
        match shape {
            crate::model::shape::ShapeObject::Picture(pic) => {
                values.push(pic.image_attr.clamped_transparency());
                if let Some(caption) = &pic.caption {
                    collect_picture_transparencies_from_paragraphs(&caption.paragraphs, values);
                }
            }
            crate::model::shape::ShapeObject::Group(group) => {
                for child in &group.children {
                    collect_picture_transparencies_from_shape(child, values);
                }
                if let Some(caption) = &group.caption {
                    collect_picture_transparencies_from_paragraphs(&caption.paragraphs, values);
                }
            }
            _ => {
                if let Some(drawing) = shape.drawing() {
                    if let Some(text_box) = &drawing.text_box {
                        collect_picture_transparencies_from_paragraphs(
                            &text_box.paragraphs,
                            values,
                        );
                    }
                    if let Some(caption) = &drawing.caption {
                        collect_picture_transparencies_from_paragraphs(&caption.paragraphs, values);
                    }
                }
            }
        }
    }

    fn parse_idx(res: &str, key: &str) -> usize {
        res.split(&format!("\"{}\":", key))
            .nth(1)
            .and_then(|s| s.split(|c: char| !c.is_ascii_digit()).next())
            .and_then(|s| s.parse().ok())
            .unwrap_or_else(|| panic!("missing {key} in {res}"))
    }

    #[test]
    fn issue1151_insert_picture_into_table_cell_is_floating_sibling() {
        let mut core = make_test_core();

        // 1×1 표 생성
        let table_res = core
            .create_table_native(0, 0, 0, 1, 1)
            .expect("create 1x1 table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");

        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            5000,
            5000,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert picture (floating)");

        // 셀 안은 그대로 비어있어야 한다 (floating 은 셀에 들어가지 않음).
        let table_ctrl =
            &core.document.sections[0].paragraphs[table_para_idx].controls[table_ctrl_idx];
        let table = match table_ctrl {
            Control::Table(t) => t,
            _ => panic!("expected Control::Table"),
        };
        let cell0_para0 = &table.cells[0].paragraphs[0];
        assert!(
            cell0_para0
                .controls
                .iter()
                .all(|c| !matches!(c, Control::Picture(_))),
            "cell 안에 picture 가 들어가면 안 된다 (floating 방식). got: {:?}",
            cell0_para0.controls
        );

        // table 같은 paragraph 의 sibling control 로 Picture 가 존재해야 한다.
        let parent_para = &core.document.sections[0].paragraphs[table_para_idx];
        let picture = parent_para
            .controls
            .iter()
            .find_map(|c| match c {
                Control::Picture(p) => Some(p.as_ref()),
                _ => None,
            })
            .expect("expected sibling Picture in parent paragraph");

        // floating 속성 검증
        assert!(
            !picture.common.treat_as_char,
            "floating picture 는 treat_as_char=false 여야 한다"
        );
        assert!(
            matches!(
                picture.common.text_wrap,
                crate::model::shape::TextWrap::Square
            ),
            "floating picture wrap=Square (어울림) 이어야 한다. got: {:?}",
            picture.common.text_wrap
        );
    }

    #[test]
    fn issue1151_v9_insert_picture_body_floating_default() {
        // [Task #1151 v9 결함 E] 한컴 native 정합: 본문 picture 신규 삽입 시 default =
        // tac=false (floating, 글자처럼 미체크). 셀 분기와 동일 패턴.
        let mut core = make_test_core();
        let image = minimal_png();
        core.insert_picture_native(
            0,
            0,
            0,
            &[], // 빈 cell_path → 본문 floating (v9 fix 후)
            &image,
            5000,
            5000,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert picture body");

        let body_para = &core.document.sections[0].paragraphs[0];
        let pic_in_body = body_para.controls.iter().find_map(|c| match c {
            Control::Picture(p) => Some(p.as_ref()),
            _ => None,
        });
        let picture = pic_in_body.expect("expected Picture in body paragraph (sibling control)");

        // 한컴 native 정합: tac=false, rel_to=Paper, wrap=Square
        assert!(
            !picture.common.treat_as_char,
            "본문 picture default = tac=false (한컴 native 정합, v9 결함 E fix)"
        );
        assert!(
            matches!(
                picture.common.horz_rel_to,
                crate::model::shape::HorzRelTo::Paper
            ),
            "본문 picture horz_rel_to = Paper (셀 분기와 동일)"
        );
        assert!(
            matches!(
                picture.common.vert_rel_to,
                crate::model::shape::VertRelTo::Paper
            ),
            "본문 picture vert_rel_to = Paper"
        );
        assert!(matches!(
            picture.common.text_wrap,
            crate::model::shape::TextWrap::Square
        ));

        // 새 paragraph 생성 안 함 — 기존 paragraph 의 sibling control 로 append
        assert_eq!(
            core.document.sections[0].paragraphs.len(),
            1,
            "본문 picture 삽입 시 새 paragraph 생성 안 함 (sibling control)"
        );
    }

    #[test]
    fn issue1452_insert_picture_returns_logical_offset_after_picture() {
        let mut core = make_test_core();
        core.insert_text_native(0, 0, 0, "abc")
            .expect("insert text");

        let image = minimal_png();
        let result = core
            .insert_picture_native(
                0,
                0,
                3,
                &[],
                &image,
                5000,
                5000,
                1,
                1,
                "png",
                "test",
                None,
                None,
            )
            .expect("insert picture body");

        assert_eq!(parse_idx(&result, "paraIdx"), 0);
        assert_eq!(parse_idx(&result, "controlIdx"), 0);
        assert_eq!(
            parse_idx(&result, "logicalOffset"),
            4,
            "본문 텍스트 'abc' 뒤에 그림 1개를 넣으면 그림 뒤 커서 offset은 4여야 한다: {result}"
        );
    }

    #[test]
    fn issue1452_enter_after_dropped_inline_picture_keeps_next_para_below_picture() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};

        fn collect_image_bboxes(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Image(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for child in &node.children {
                collect_image_bboxes(child, out);
            }
        }

        fn collect_para_end_runs(
            node: &RenderNode,
            out: &mut Vec<(usize, Option<usize>, f64, f64, f64, f64)>,
        ) {
            if let RenderNodeType::TextRun(run) = &node.node_type {
                if run.is_para_end {
                    if let Some(para_idx) = run.para_index {
                        out.push((
                            para_idx,
                            run.char_start,
                            node.bbox.x,
                            node.bbox.y,
                            node.bbox.width,
                            node.bbox.height,
                        ));
                    }
                }
            }
            for child in &node.children {
                collect_para_end_runs(child, out);
            }
        }

        let mut core = make_test_core();
        let image = minimal_png();
        let pic_w = 30000u32;
        let pic_h = 9000u32;

        let result = core
            .insert_picture_native(
                0,
                0,
                0,
                &[],
                &image,
                pic_w,
                pic_h,
                1,
                1,
                "png",
                "drop",
                None,
                None,
            )
            .expect("insert dropped picture");
        let ctrl_idx = parse_idx(&result, "controlIdx");
        let logical_offset = parse_idx(&result, "logicalOffset");

        core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"treatAsChar":true}"#)
            .expect("dropped picture becomes treat-as-char");
        core.split_paragraph_native(0, 0, logical_offset, None)
            .expect("Enter after dropped picture");

        assert_eq!(
            core.document.sections[0].paragraphs.len(),
            2,
            "그림 뒤 Enter 는 새 빈 문단을 만들어야 한다"
        );
        assert_eq!(
            core.document.sections[0].paragraphs[0].line_segs[0].line_height, pic_h as i32,
            "TAC 그림만 남은 첫 문단은 그림 높이를 줄 높이로 유지해야 한다"
        );
        assert!(
            core.document.sections[0].paragraphs[1].line_segs[0].line_height < pic_h as i32 / 2,
            "새 빈 문단은 그림 높이를 물려받지 않고 기본 줄 높이로 시작해야 한다"
        );

        let tree = core.build_page_tree(0).expect("build page tree");
        let mut images = Vec::new();
        collect_image_bboxes(&tree.root, &mut images);
        assert_eq!(images.len(), 1, "drop 그림 ImageNode 1개 필요");

        let mut para_ends = Vec::new();
        collect_para_end_runs(&tree.root, &mut para_ends);
        let image = images[0];
        let image_right = image.0 + image.2;
        let image_bottom = image.1 + image.3;
        let para0_end = para_ends
            .iter()
            .find(|(para_idx, _, _, _, _, _)| *para_idx == 0)
            .expect("첫 문단 끝 표시");
        let para1_end = para_ends
            .iter()
            .find(|(para_idx, _, _, _, _, _)| *para_idx == 1)
            .expect("새 빈 문단 끝 표시");

        assert_eq!(
            para0_end.1,
            Some(logical_offset),
            "첫 문단 끝 표시는 그림 뒤 logical offset에 놓여야 한다"
        );
        assert!(
            para0_end.2 >= image_right - 0.5,
            "첫 문단부호 x는 그림 뒤에 있어야 한다: mark_x={}, image_right={}",
            para0_end.2,
            image_right
        );
        assert!(
            para1_end.3 >= image_bottom - 0.5,
            "새 빈 문단부호는 그림 아래 줄에 있어야 한다: mark_y={}, image_bottom={}",
            para1_end.3,
            image_bottom
        );
    }

    #[test]
    fn issue1452_picture_text_wrap_updates_hwp_attr_bits() {
        let mut core = make_test_core();
        let image = minimal_png();
        core.insert_picture_native(
            0,
            0,
            0,
            &[],
            &image,
            5000,
            5000,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert picture body");

        {
            let pic = match &mut core.document.sections[0].paragraphs[0].controls[0] {
                Control::Picture(p) => p.as_mut(),
                _ => panic!("expected picture"),
            };
            pic.common.attr |= 1 << 30;
        }

        let cases = [
            (
                "InFrontOfText",
                crate::model::shape::TextWrap::InFrontOfText,
                3u32,
            ),
            (
                "BehindText",
                crate::model::shape::TextWrap::BehindText,
                2u32,
            ),
            (
                "TopAndBottom",
                crate::model::shape::TextWrap::TopAndBottom,
                1u32,
            ),
            ("Square", crate::model::shape::TextWrap::Square, 0u32),
        ];

        for (name, expected_wrap, expected_bits) in cases {
            let json = format!(r#"{{"textWrap":"{}"}}"#, name);
            core.set_picture_properties_native(0, 0, 0, &json)
                .unwrap_or_else(|err| panic!("set textWrap={name} failed: {err}"));
            let pic = match &core.document.sections[0].paragraphs[0].controls[0] {
                Control::Picture(p) => p.as_ref(),
                _ => panic!("expected picture"),
            };
            assert_eq!(pic.common.text_wrap, expected_wrap);
            assert_eq!(
                (pic.common.attr >> 21) & 0x07,
                expected_bits,
                "HWP 저장용 attr textWrap bit가 stale이면 안 된다: {name}"
            );
            assert_ne!(
                pic.common.attr & (1 << 30),
                0,
                "알 수 없는 원본 attr 비트는 보존되어야 한다"
            );
        }
    }

    #[test]
    fn issue1452_picture_transparency_props_roundtrip() {
        let mut core = make_test_core();
        let image = minimal_png();
        core.insert_picture_native(
            0,
            0,
            0,
            &[],
            &image,
            5000,
            5000,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert picture body");

        core.set_picture_properties_native(0, 0, 0, r#"{"transparency":50}"#)
            .expect("set transparency");
        let props = core
            .get_picture_properties_native(0, 0, 0)
            .expect("get picture properties");
        assert!(
            props.contains(r#""transparency":50"#),
            "그림 속성 JSON은 투명도 50%를 반환해야 한다: {props}"
        );

        let pic = match &core.document.sections[0].paragraphs[0].controls[0] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("expected picture"),
        };
        assert_eq!(pic.image_attr.clamped_transparency(), 50);
        assert!((pic.image_attr.opacity() - 0.5).abs() < f64::EPSILON);

        core.set_picture_properties_native(0, 0, 0, r#"{"transparency":200}"#)
            .expect("set clamped transparency");
        let pic = match &core.document.sections[0].paragraphs[0].controls[0] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("expected picture"),
        };
        assert_eq!(
            pic.image_attr.clamped_transparency(),
            100,
            "속성 API로 들어온 범위 밖 투명도는 0~100으로 clamp되어야 한다"
        );
    }

    #[test]
    fn issue1452_picture_transparency_samples_parse_as_ui_percent() {
        for path in ["samples/투명도0-50.hwp", "samples/투명도0-50.hwpx"] {
            let data =
                std::fs::read(path).unwrap_or_else(|err| panic!("fixture 읽기 실패 {path}: {err}"));
            let core =
                DocumentCore::from_bytes(&data).unwrap_or_else(|err| panic!("parse {path}: {err}"));
            let transparencies = collect_picture_transparencies(&core.document);
            assert!(
                transparencies.len() >= 2,
                "샘플에는 최소 두 개의 그림이 있어야 한다: {path}, got {transparencies:?}"
            );
            assert_eq!(
                &transparencies[..2],
                &[0, 50],
                "샘플 첫 번째/두 번째 그림 투명도는 각각 0%, 50%여야 한다: {path}"
            );
        }
    }

    #[test]
    fn issue1452_picture_transparency_samples_render_once_with_opacity() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};

        fn collect_images(node: &RenderNode, out: &mut Vec<(Option<usize>, Option<usize>, f64)>) {
            if let RenderNodeType::Image(img) = &node.node_type {
                out.push((img.para_index, img.control_index, img.opacity));
            }
            for child in &node.children {
                collect_images(child, out);
            }
        }

        for path in ["samples/투명도0-50.hwp", "samples/투명도0-50.hwpx"] {
            let data =
                std::fs::read(path).unwrap_or_else(|err| panic!("fixture 읽기 실패 {path}: {err}"));
            let core =
                DocumentCore::from_bytes(&data).unwrap_or_else(|err| panic!("parse {path}: {err}"));
            let tree = core
                .build_page_tree(0)
                .unwrap_or_else(|err| panic!("render tree {path}: {err}"));
            let mut images = Vec::new();
            collect_images(&tree.root, &mut images);

            assert_eq!(
                images.len(),
                2,
                "투명도 샘플의 그림은 두 번만 렌더되어야 한다: {path}, got {images:?}"
            );

            let mut identities = images
                .iter()
                .map(|(para, control, _)| (*para, *control))
                .collect::<Vec<_>>();
            identities.sort_unstable();
            identities.dedup();
            assert_eq!(
                identities.len(),
                2,
                "같은 그림 control 이 중복 렌더되면 안 된다: {path}, got {images:?}"
            );

            let mut opacities = images
                .iter()
                .map(|(_, _, opacity)| (opacity * 100.0).round() as i32)
                .collect::<Vec<_>>();
            opacities.sort_unstable();
            assert_eq!(
                opacities,
                vec![50, 100],
                "렌더 트리 불투명도는 투명도 0/50%를 100/50%로 보존해야 한다: {path}"
            );
        }
    }

    #[test]
    fn issue1452_enter_after_second_tac_picture_keeps_both_pictures() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};

        fn collect_images(node: &RenderNode, out: &mut Vec<(Option<usize>, Option<usize>, f64)>) {
            if let RenderNodeType::Image(img) = &node.node_type {
                out.push((img.para_index, img.control_index, img.opacity));
            }
            for child in &node.children {
                collect_images(child, out);
            }
        }

        let data = std::fs::read("samples/투명도0-50.hwp")
            .expect("fixture 읽기 실패 samples/투명도0-50.hwp");
        let mut core = DocumentCore::from_bytes(&data).expect("parse samples/투명도0-50.hwp");

        core.split_paragraph_native(0, 0, 2, None)
            .expect("두 번째 TAC 그림 뒤 Enter");

        assert_eq!(
            core.document.sections[0].paragraphs.len(),
            2,
            "그림 뒤 Enter 는 새 빈 문단을 만들어야 한다"
        );
        assert!(
            core.document.sections[0].paragraphs[0].line_segs.len() >= 2,
            "원래 문단은 두 TAC 그림 줄을 유지해야 한다: {:?}",
            core.document.sections[0].paragraphs[0].line_segs
        );

        let tree = core.build_page_tree(0).expect("build page tree");
        let mut images = Vec::new();
        collect_images(&tree.root, &mut images);
        assert_eq!(
            images.len(),
            2,
            "Enter 후에도 두 그림이 모두 렌더되어야 한다: {images:?}"
        );

        let mut identities = images
            .iter()
            .map(|(para, control, _)| (*para, *control))
            .collect::<Vec<_>>();
        identities.sort_unstable();
        identities.dedup();
        assert_eq!(
            identities.len(),
            2,
            "두 그림 control 이 각각 렌더되어야 한다: {images:?}"
        );
    }

    #[test]
    fn issue1151_invalid_cell_path_returns_error() {
        let mut core = make_test_core();
        let _ = core
            .create_table_native(0, 0, 0, 1, 1)
            .expect("create table");
        let bad_path: Vec<(usize, usize, usize)> = vec![(0, 5, 0)]; // cell 5 는 1×1 표에 없음
        let image = minimal_png();
        let res = core.insert_picture_native(
            0, 0, 0, &bad_path, &image, 5000, 5000, 1, 1, "png", "test", None, None,
        );
        assert!(
            res.is_err(),
            "out-of-range cell path → Err 기대, got {res:?}"
        );
    }
}

#[cfg(test)]
mod issue_1151_v2_tac_toggle_tests {
    //! Issue #1151 v2: floating picture → "글자처럼 취급" 토글 시 한컴 정합 (H1).
    //!
    //! 한컴 산출물 분석 (samples/tac-verify/scenario-{a,b,c,d}-after.hwp) 결과:
    //! tac false→true 토글 시 picture 의 control 위치는 불변이고, 4 가지 필드만
    //! 갱신된다. (a) treat_as_char=true, (b) horz/vert_rel_to=Para, (c) h/v_offset=0,
    //! (d) parent paragraph 의 line_segs[0] 의 line_height = picture height,
    //!     text_height = picture height, baseline_distance = round(lh*0.85).
    //! paragraph.text / char_offsets / paragraph 수 변화 없음.

    use super::*;
    use crate::model::document::{Document, Section, SectionDef};
    use crate::model::image::{ImageAttr, Picture};
    use crate::model::page::PageDef;
    use crate::model::paragraph::LineSeg;
    use crate::model::shape::{CommonObjAttr, HorzRelTo, ShapeComponentAttr, TextWrap, VertRelTo};

    fn make_test_core() -> DocumentCore {
        let mut doc = Document::default();
        doc.sections.push(Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 59528,
                    height: 84188,
                    margin_left: 8504,
                    margin_right: 8504,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            paragraphs: vec![Paragraph::default()],
            trailing_lists: None,
            raw_stream: None,
            raw_provenance: None,
        });
        let mut core = DocumentCore::new_empty();
        core.set_document(doc);
        core
    }

    fn minimal_png() -> Vec<u8> {
        vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x00, 0x00, 0x00,
            0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ]
    }

    fn parse_idx(res: &str, key: &str) -> usize {
        res.split(&format!("\"{}\":", key))
            .nth(1)
            .and_then(|s| s.split(|c: char| !c.is_ascii_digit()).next())
            .and_then(|s| s.parse().ok())
            .unwrap_or_else(|| panic!("missing {key} in {res}"))
    }

    /// 본문 (또는 임의 paragraph) 에 floating picture 를 직접 push 한다.
    /// 한컴이 만든 floating picture 의 model 상태 (tac=false, Paper-relative, offset 있음)
    /// 와 동등.
    fn push_body_floating_picture(
        para: &mut Paragraph,
        width_hu: u32,
        height_hu: u32,
        offset_h: u32,
        offset_v: u32,
        bin_id: u16,
    ) -> usize {
        let common_attr: u32 = (1 << 3) | (1 << 8) | (4 << 15) | (2 << 18);
        let pic = Picture {
            common: CommonObjAttr {
                ctrl_id: 0x67736F20,
                attr: common_attr,
                treat_as_char: false,
                vert_rel_to: VertRelTo::Paper,
                horz_rel_to: HorzRelTo::Paper,
                text_wrap: TextWrap::Square,
                horizontal_offset: offset_h,
                vertical_offset: offset_v,
                width: width_hu,
                height: height_hu,
                z_order: 0,
                ..Default::default()
            },
            shape_attr: ShapeComponentAttr {
                original_width: width_hu,
                original_height: height_hu,
                current_width: width_hu,
                current_height: height_hu,
                ..Default::default()
            },
            border_x: [0i32, 0, width_hu as i32, 0],
            border_y: [width_hu as i32, height_hu as i32, 0, height_hu as i32],
            image_attr: ImageAttr {
                bin_data_id: bin_id,
                ..Default::default()
            },
            ..Default::default()
        };
        let idx = para.controls.len();
        para.controls.push(Control::Picture(Box::new(pic)));
        para.ctrl_data_records.push(None);
        idx
    }

    /// 한컴 산출물에서 관찰된 baseline 비율: lh × 0.85 (round).
    fn expected_baseline(lh: i32) -> i32 {
        (lh as f64 * 0.85).round() as i32
    }

    // ─── Scenario A 등가 ───────────────────────────────────────────────
    #[test]
    fn tac_toggle_table_sibling_floating_to_inline() {
        let mut core = make_test_core();

        // 1×1 표 생성
        let table_res = core
            .create_table_native(0, 0, 0, 1, 1)
            .expect("create 1x1 table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");

        // 셀 안 floating picture 삽입 (v1 path, h=5331 HU)
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();
        let pic_w = 5977u32;
        let pic_h = 5331u32;
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            pic_w,
            pic_h,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert floating picture in cell");

        // picture 는 표 sibling 위치 (= 마지막 control)
        let pic_ctrl_idx = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        let before_paragraph_count = core.document.sections[0].paragraphs.len();
        let before_controls_count = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len();

        // tac false→true 토글
        let res = core.set_picture_properties_native(
            0,
            table_para_idx,
            pic_ctrl_idx,
            r#"{"treatAsChar":true}"#,
        );
        assert!(res.is_ok(), "set_picture_properties_native failed: {res:?}");

        let para = &core.document.sections[0].paragraphs[table_para_idx];
        let pic = match &para.controls[pic_ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("picture not at expected ctrl_idx"),
        };

        // (1) picture 위치 / paragraph 수 불변
        assert_eq!(para.controls.len(), before_controls_count);
        assert_eq!(
            core.document.sections[0].paragraphs.len(),
            before_paragraph_count
        );

        // (2) 4 필드 갱신
        assert!(pic.common.treat_as_char, "treat_as_char true");
        assert_eq!(pic.common.attr & 0x01, 0x01, "attr 비트 0 셋");
        assert!(
            matches!(pic.common.horz_rel_to, HorzRelTo::Para),
            "horz_rel_to=Para, got {:?}",
            pic.common.horz_rel_to
        );
        assert!(
            matches!(pic.common.vert_rel_to, VertRelTo::Para),
            "vert_rel_to=Para, got {:?}",
            pic.common.vert_rel_to
        );
        assert_eq!(pic.common.horizontal_offset, 0, "h_offset=0");
        assert_eq!(pic.common.vertical_offset, 0, "v_offset=0");

        // (3) LINE_SEG[0] 갱신
        let seg = &para.line_segs[0];
        assert_eq!(
            seg.line_height, pic_h as i32,
            "line_segs[0].line_height = picture height"
        );
        assert_eq!(
            seg.text_height, pic_h as i32,
            "line_segs[0].text_height = picture height"
        );
        assert_eq!(
            seg.baseline_distance,
            expected_baseline(pic_h as i32),
            "line_segs[0].baseline_distance = round(lh*0.85)"
        );

        // (4) text / char_offsets 불변 (sentinel char 추가하지 않음)
        assert_eq!(para.text, "");
        assert_eq!(para.char_offsets.len(), 0);
    }

    // ─── [Task #1151 v8 결함 A regression] v1 셀 floating 의 초기 rel_to=Paper ─
    //
    // 사용자 한컴 native 시연 (2026-05-30): 한컴이 셀 안 picture 신규 삽입 시
    // 가로/세로 기준 = "종이" (Paper). v1 plan 의 incellpicture.hwp dump 분석 정합.
    // v1 구현이 Page 로 잘못 설정한 결함을 정정.
    #[test]
    fn v8_cell_floating_picture_uses_paper_rel_to() {
        let mut core = make_test_core();
        let table_res = core
            .create_table_native(0, 0, 0, 1, 1)
            .expect("create 1x1 table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            5977,
            5331,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert floating picture in cell");
        let pic_ctrl_idx = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        let para = &core.document.sections[0].paragraphs[table_para_idx];
        let pic = match &para.controls[pic_ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("not Picture"),
        };

        // (A) typed field 가 Paper
        assert!(
            matches!(pic.common.horz_rel_to, HorzRelTo::Paper),
            "horz_rel_to = Paper (한컴 native default), got {:?}",
            pic.common.horz_rel_to
        );
        assert!(
            matches!(pic.common.vert_rel_to, VertRelTo::Paper),
            "vert_rel_to = Paper, got {:?}",
            pic.common.vert_rel_to
        );

        // (B) attr 비트 정합 — bit 3-4 (vert) = 0, bit 8-10 (horz) = 0 (둘 다 Paper)
        let bits_vert = (pic.common.attr >> 3) & 0b11;
        let bits_horz = (pic.common.attr >> 8) & 0b111;
        assert_eq!(bits_vert, 0, "attr bits 3-4 = Paper(0)");
        assert_eq!(bits_horz, 0, "attr bits 8-10 = Paper(0)");

        // (C) tac=false, wrap=Square 그대로
        assert!(!pic.common.treat_as_char);
        assert!(matches!(
            pic.common.text_wrap,
            crate::model::shape::TextWrap::Square
        ));
    }

    // ─── [Task #1151 v9 결함 D regression v2] 큰 picture 2 장 wrap 시나리오 ───
    //
    // 사용자 시연 (2026-05-30 후속): 큰 picture 2 장 (page 폭 초과) 글자처럼 토글 시
    // 한컴 native 는 wrap (다음 line). Stage 23 fix 첫 버전은 pic_y 결정이 pic_x wrap
    // 처리 전이라 wrap 후 line_top_y 가 갱신됐어도 pic_y 가 wrap 전 값 → 두 picture
    // 같은 위치 겹침. Fix: pic_y 결정을 pic_x 뒤로 옮김 (wrap 후 state 반영).
    #[test]
    fn v9_two_large_pictures_wrap_to_next_line() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};
        fn collect_image_bboxes(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Image(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for child in &node.children {
                collect_image_bboxes(child, out);
            }
        }

        let mut core = make_test_core();
        let table_res = core.create_table_native(0, 0, 0, 1, 1).expect("table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();

        // 큰 picture 2 장 — 각 80mm × 60mm (22680 × 17010 HU)
        // page 본문 폭 ≈ 150mm. 두 picture 합 160mm > 150mm → wrap 발생해야 함.
        let pic_w = 22680u32;
        let pic_h = 17010u32;

        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            pic_w,
            pic_h,
            1,
            1,
            "png",
            "p1",
            None,
            None,
        )
        .expect("insert pic1");
        let pic1_ctrl = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        core.set_picture_properties_native(0, table_para_idx, pic1_ctrl, r#"{"treatAsChar":true}"#)
            .expect("toggle pic1");

        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            pic_w,
            pic_h,
            1,
            1,
            "png",
            "p2",
            None,
            None,
        )
        .expect("insert pic2");
        let pic2_ctrl = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        core.set_picture_properties_native(0, table_para_idx, pic2_ctrl, r#"{"treatAsChar":true}"#)
            .expect("toggle pic2");

        let tree = core.build_page_tree_cached(0).expect("build");
        let mut images = vec![];
        collect_image_bboxes(&tree.root, &mut images);
        let pic_h_px = pic_h as f64 * 96.0 / 7200.0;

        assert_eq!(images.len(), 2, "두 picture 모두 render 되어야 함");
        let (x1, y1, _, _) = images[0];
        let (x2, y2, _, _) = images[1];

        // (A) 둘째 picture y 가 첫 picture y + pic_h 만큼 진행 (wrap)
        let y_diff = y2 - y1;
        assert!(
            (y_diff - pic_h_px).abs() < 1.0,
            "wrap: y_diff {:.2} ≈ pic_h {:.2} (한 picture height 만큼 진행) — got y1={}, y2={}",
            y_diff,
            pic_h_px,
            y1,
            y2
        );

        // (B) x 동일 (wrap 후 둘째 picture 가 새 line 의 좌측에서 시작)
        assert!(
            (x1 - x2).abs() < 1.0,
            "wrap: x 동일 (둘 다 새 line 의 좌측) — got x1={}, x2={}",
            x1,
            x2
        );
    }

    #[test]
    fn v9_two_tac_pictures_horizontal_distribute() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};
        fn collect_image_bboxes(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Image(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for child in &node.children {
                collect_image_bboxes(child, out);
            }
        }

        let mut core = make_test_core();
        let table_res = core.create_table_native(0, 0, 0, 1, 1).expect("table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();

        // picture 1 삽입 + tac
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            5670,
            5670,
            1,
            1,
            "png",
            "test1",
            None,
            None,
        )
        .expect("insert pic1");
        let pic1_ctrl = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        core.set_picture_properties_native(0, table_para_idx, pic1_ctrl, r#"{"treatAsChar":true}"#)
            .expect("toggle pic1");

        // picture 2 삽입 + tac
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            5670,
            5670,
            1,
            1,
            "png",
            "test2",
            None,
            None,
        )
        .expect("insert pic2");
        let pic2_ctrl = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        core.set_picture_properties_native(0, table_para_idx, pic2_ctrl, r#"{"treatAsChar":true}"#)
            .expect("toggle pic2");

        // render tree 의 image bbox 검증
        let tree = core.build_page_tree_cached(0).expect("build page 0");
        let mut images = vec![];
        collect_image_bboxes(&tree.root, &mut images);
        assert_eq!(images.len(), 2, "두 picture 모두 render 되어야 함");

        let (x1, y1, w1, _h1) = images[0];
        let (x2, y2, _w2, _h2) = images[1];

        // (A) y 동일 (한 line) — 가로 분배 정합
        assert!(
            (y1 - y2).abs() < 0.5,
            "두 picture y 동일 (가로 분배) — got y1={}, y2={}",
            y1,
            y2
        );

        // (B) x 다름 (가로 누적) — pic2 x = pic1 x + pic1 width
        assert!(
            x2 > x1 + 0.5,
            "두 picture x 다름 (가로 누적) — got x1={}, x2={}",
            x1,
            x2
        );
        assert!(
            (x2 - (x1 + w1)).abs() < 0.5,
            "pic2 x ≈ pic1 x + pic1 width — got x1={}, x2={}, w1={}",
            x1,
            x2,
            w1
        );
    }

    // ─── Scenario D 등가 ───────────────────────────────────────────────
    #[test]
    fn tac_toggle_body_floating_to_inline() {
        let mut core = make_test_core();
        let pic_h = 19019u32;
        let pic_w = 20863u32;
        let ctrl_idx = {
            let para = &mut core.document.sections[0].paragraphs[0];
            push_body_floating_picture(para, pic_w, pic_h, 13428, 13568, 1)
        };

        let res = core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"treatAsChar":true}"#);
        assert!(res.is_ok(), "set_picture_properties_native failed: {res:?}");

        let para = &core.document.sections[0].paragraphs[0];
        let pic = match &para.controls[ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("picture not at expected ctrl_idx"),
        };

        assert!(pic.common.treat_as_char);
        assert!(matches!(pic.common.horz_rel_to, HorzRelTo::Para));
        assert!(matches!(pic.common.vert_rel_to, VertRelTo::Para));
        assert_eq!(pic.common.horizontal_offset, 0);
        assert_eq!(pic.common.vertical_offset, 0);

        let seg = &para.line_segs[0];
        assert_eq!(seg.line_height, pic_h as i32);
        assert_eq!(seg.text_height, pic_h as i32);
        assert_eq!(seg.baseline_distance, expected_baseline(pic_h as i32));

        assert_eq!(para.text, "");
        assert_eq!(para.char_offsets.len(), 0);
    }

    // ─── Scenario C 등가 ───────────────────────────────────────────────
    #[test]
    fn tac_toggle_3x3_center_cell_floating_to_inline() {
        let mut core = make_test_core();

        let table_res = core
            .create_table_native(0, 0, 0, 3, 3)
            .expect("create 3x3 table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");

        // (1,1) 중앙 셀의 cell_path: (outer_ctrl_idx, row, col)
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 1, 1)];
        let image = minimal_png();
        let pic_w = 5434u32;
        let pic_h = 4847u32;
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            pic_w,
            pic_h,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert floating picture in center cell");

        let pic_ctrl_idx = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;
        let res = core.set_picture_properties_native(
            0,
            table_para_idx,
            pic_ctrl_idx,
            r#"{"treatAsChar":true}"#,
        );
        assert!(res.is_ok(), "set_picture_properties_native failed: {res:?}");

        let para = &core.document.sections[0].paragraphs[table_para_idx];
        let pic = match &para.controls[pic_ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("picture not at expected ctrl_idx"),
        };
        assert!(pic.common.treat_as_char);
        assert_eq!(pic.common.horizontal_offset, 0);
        assert_eq!(pic.common.vertical_offset, 0);
        assert_eq!(para.line_segs[0].line_height, pic_h as i32);
        assert_eq!(
            para.line_segs[0].baseline_distance,
            expected_baseline(pic_h as i32)
        );
    }

    // ─── [Task #1151 v5] v1 path → tac toggle → page tree cache invalidate 검증 ─
    //
    // 사용자 보고 (2026-05-30): "rhwp 신규 표 + 셀 안 이미지 → tac 토글 시
    // 시각 변화 없음". 진단 결과 model + composer + paragraph_layout 모두 정상
    // 동작 (picture 가 표 아래 정확 위치 156.9 px 에 inline 렌더) 인데, studio
    // 가 stale page tree 받음. root cause: set_picture_properties_native 의
    // invalidate_page_tree_cache 호출 누락 — 다른 picture/shape setter (셀 picture
    // by_path / 셀 shape by_path / header-footer / shape 등) 는 모두 호출.
    //
    // 본 테스트는 v1 path → tac toggle 후 build_page_render_tree 가 picture 가
    // 표 아래로 이동한 새 위치로 ImageNode 를 emit 하는지 검증 — cache 갱신 정합.
    #[test]
    fn v5_tac_toggle_invalidates_page_tree_and_emits_inline_picture_below_table() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};
        fn collect_image_bboxes(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Image(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for child in &node.children {
                collect_image_bboxes(child, out);
            }
        }
        fn collect_table_bboxes(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Table(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for child in &node.children {
                collect_table_bboxes(child, out);
            }
        }

        let mut core = make_test_core();
        let table_res = core
            .create_table_native(0, 0, 0, 1, 1)
            .expect("create 1x1 table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();
        let pic_w = 5977u32;
        let pic_h = 5331u32;
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            pic_w,
            pic_h,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert floating picture in cell");
        let pic_ctrl_idx = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;

        // toggle 전: build_page_tree_cached 호출 → cache 채움.
        let tree_before = core
            .build_page_tree_cached(0)
            .expect("build_page_tree_cached pre-toggle");
        let mut image_before: Vec<(f64, f64, f64, f64)> = vec![];
        collect_image_bboxes(&tree_before.root, &mut image_before);
        assert_eq!(image_before.len(), 1, "toggle 전 ImageNode 1 개 필요");
        let (_x0, y_before, _w0, _h0) = image_before[0];

        // tac false → true 토글
        core.set_picture_properties_native(
            0,
            table_para_idx,
            pic_ctrl_idx,
            r#"{"treatAsChar":true}"#,
        )
        .expect("toggle");

        // toggle 후: build_page_tree_cached 다시 호출. fix 적용 시 invalidate_page_tree_cache
        // 가 작동하여 새 tree 반환 (picture 위치 = 표 아래). fix 미적용 시 stale cache 반환.
        let tree_after = core
            .build_page_tree_cached(0)
            .expect("build_page_tree_cached post-toggle");
        let mut image_after: Vec<(f64, f64, f64, f64)> = vec![];
        collect_image_bboxes(&tree_after.root, &mut image_after);
        let mut table_after: Vec<(f64, f64, f64, f64)> = vec![];
        collect_table_bboxes(&tree_after.root, &mut table_after);

        assert_eq!(image_after.len(), 1, "toggle 후 ImageNode 1 개 필요");
        assert_eq!(table_after.len(), 1, "toggle 후 Table 1 개 필요");
        let (_x_a, y_after, _w_a, _h_a) = image_after[0];
        let (_tx, ty, _tw, th) = table_after[0];
        let table_bottom = ty + th;

        // (A) cache invalidate 검증: toggle 전후 picture y 가 다름 (stale cache 아님).
        assert!(
            (y_before - y_after).abs() > 0.5,
            "FAIL: page tree cache invalidate 누락 — toggle 후에도 picture y 동일 (before={}, after={})",
            y_before,
            y_after
        );

        // (B) toggle 후 picture 가 표 아래 위치 (한컴 정합).
        assert!(
            y_after > table_bottom,
            "FAIL: picture 가 표 아래에 미배치 — picture y={}, table bottom={}",
            y_after,
            table_bottom
        );
    }

    // ─── [Task #1151 v6] 한컴 정합 (scenario-a-after.hwp) render tree baseline ──
    //
    // v6 root cause 진단 베이스라인 — 한컴 정합 model 의 render tree 가 표를
    // 정확한 셀 size 로 그리고 picture 가 표 아래에 배치됨을 확인. v6 fix
    // (Table::update_ctrl_dimensions 가 self.common 동기화) 가 적용된 후 rhwp
    // v1 path + 셀 size 조절 + tac toggle 의 render tree 가 이 baseline 과 같은
    // 패턴 (image y > table bottom) 을 따르는지가 v6 fix 정합 기준.
    #[test]
    fn v6_render_tree_scenario_a_after_baseline() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};
        fn collect_image(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Image(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for c in &node.children {
                collect_image(c, out);
            }
        }
        fn collect_table(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Table(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for c in &node.children {
                collect_table(c, out);
            }
        }

        let bytes = std::fs::read("samples/tac-verify/scenario-a-after.hwp")
            .expect("read scenario-a-after.hwp");
        let doc = crate::parser::parse_hwp(&bytes).expect("parse scenario-a-after.hwp");
        let mut core = DocumentCore::new_empty();
        core.set_document(doc);
        let tree = core.build_page_tree_cached(0).expect("build page 0");
        let mut images = vec![];
        let mut tables = vec![];
        collect_image(&tree.root, &mut images);
        collect_table(&tree.root, &mut tables);

        // baseline 단언: 표 와 picture 가 분리되어 표 아래에 picture 배치
        assert_eq!(tables.len(), 1, "한컴 정합 표 1개");
        assert_eq!(images.len(), 1, "한컴 정합 picture 1개");
        let (_tx, ty, _tw, th) = tables[0];
        let (_ix, iy, _iw, _ih) = images[0];
        assert!(
            iy > ty + th,
            "한컴 baseline: picture 가 표 아래 (iy={}, table_bottom={})",
            iy,
            ty + th
        );
    }

    // ─── [Task #1151 v6 regression] rhwp v1 path + 셀 height 조절 + tac toggle ─
    //
    // Root cause: Table::update_ctrl_dimensions 가 raw_ctrl_data 만 갱신하고
    // self.common.width / self.common.height 는 동기화하지 않아 paragraph_layout 의
    // v3 helper 가 stale 값 (cell 조절 전) 을 사용 → picture 가 표 아래로 충분히
    // 안 밀려나고 표 박스 안에 들어감 (사용자 보고 2026-05-30).
    //
    // Fix: update_ctrl_dimensions 에서 self.common.width / height 동기화.
    // 검증: cell.height = 11498 조절 후 tac toggle → table.common.height == 11498
    // 및 picture y > table bottom.
    #[test]
    fn v6_resize_cell_then_tac_toggle_picture_below_table() {
        use crate::renderer::render_tree::{RenderNode, RenderNodeType};
        fn collect_image(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Image(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for c in &node.children {
                collect_image(c, out);
            }
        }
        fn collect_table(node: &RenderNode, out: &mut Vec<(f64, f64, f64, f64)>) {
            if matches!(node.node_type, RenderNodeType::Table(_)) {
                out.push((node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height));
            }
            for c in &node.children {
                collect_table(c, out);
            }
        }

        let mut core = make_test_core();
        let table_res = core.create_table_native(0, 0, 0, 1, 1).expect("table");
        let table_para_idx = parse_idx(&table_res, "paraIdx");
        let table_ctrl_idx = parse_idx(&table_res, "controlIdx");

        // 셀 height 를 한컴 정합 size (12498 HU) 와 유사하게 조절.
        // default cell.height = 1282 → delta = 12498 - 1282 = 11216
        core.resize_table_cells_native(
            0,
            table_para_idx,
            table_ctrl_idx,
            r#"[{"cellIdx":0,"heightDelta":11216}]"#,
        )
        .expect("resize cell");

        // v6 fix 1: resize 후 table.common.height 가 cell.height 와 동기화
        let table =
            match &core.document.sections[0].paragraphs[table_para_idx].controls[table_ctrl_idx] {
                Control::Table(t) => t,
                _ => panic!(),
            };
        assert_eq!(
            table.common.height, 11498,
            "v6 fix: table.common.height 가 cell 조절 후 동기화 (raw_ctrl_data 뿐 아니라 self.common 도)"
        );
        assert_eq!(table.cells[0].height, 11498);

        // picture 삽입 (v1 path)
        let cell_path: Vec<(usize, usize, usize)> = vec![(table_ctrl_idx, 0, 0)];
        let image = minimal_png();
        core.insert_picture_native(
            0,
            table_para_idx,
            0,
            &cell_path,
            &image,
            5977,
            5331,
            1,
            1,
            "png",
            "test",
            None,
            None,
        )
        .expect("insert");
        let pic_ctrl_idx = core.document.sections[0].paragraphs[table_para_idx]
            .controls
            .len()
            - 1;

        // tac toggle
        core.set_picture_properties_native(
            0,
            table_para_idx,
            pic_ctrl_idx,
            r#"{"treatAsChar":true}"#,
        )
        .expect("toggle");

        // v6 fix 2: render tree 의 picture 가 표 box 아래에 배치되는지 확인.
        let tree = core.build_page_tree_cached(0).expect("build page 0");
        let mut images = vec![];
        let mut tables = vec![];
        collect_image(&tree.root, &mut images);
        collect_table(&tree.root, &mut tables);
        assert_eq!(tables.len(), 1);
        assert_eq!(images.len(), 1);
        let (_tx, ty, _tw, th) = tables[0];
        let (_ix, iy, _iw, _ih) = images[0];
        assert!(
            iy > ty + th,
            "v6 fix: picture 가 표 아래 (iy={}, table_bottom={}) — table.common.height 동기화 정합",
            iy,
            ty + th
        );
    }

    // ─── 이미 tac=true 인 picture 의 다른 속성 변경 — migration 미진입 ─────
    #[test]
    fn tac_toggle_when_already_tac_true_no_migration() {
        let mut core = make_test_core();
        let pic_h = 5000u32;
        let ctrl_idx = {
            let para = &mut core.document.sections[0].paragraphs[0];
            push_body_floating_picture(para, 5000, pic_h, 1000, 1000, 1)
        };

        // 먼저 tac=true 로 마이그레이션
        core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"treatAsChar":true}"#)
            .expect("first migration");
        let lh_after_first = core.document.sections[0].paragraphs[0].line_segs[0].line_height;

        // 두 번째 호출: tac 변경 없이 다른 속성 변경 — migration 미진입
        core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"brightness":50}"#)
            .expect("second call no-op for migration");

        let para = &core.document.sections[0].paragraphs[0];
        // line_height 가 더 자라지 않아야 함 (이미 picture height 인 채로 유지)
        assert_eq!(para.line_segs[0].line_height, lh_after_first);
        // brightness 는 적용됨
        let pic = match &para.controls[ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!(),
        };
        assert_eq!(pic.image_attr.brightness, 50);
    }

    // ─── tac=true → false 토글 — 빈 그림 문단 LINE_SEG 재구성 ──────────
    #[test]
    fn tac_toggle_true_to_false_restores_empty_picture_para_line_seg() {
        let mut core = make_test_core();
        let pic_h = 5000u32;
        let ctrl_idx = {
            let para = &mut core.document.sections[0].paragraphs[0];
            push_body_floating_picture(para, 5000, pic_h, 1000, 1000, 1)
        };
        // 먼저 tac=true 로
        core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"treatAsChar":true}"#)
            .expect("forward migration");
        let lh_after_forward = core.document.sections[0].paragraphs[0].line_segs[0].line_height;
        assert_eq!(lh_after_forward, pic_h as i32);

        // tac=false 로 — 빈 그림 전용 문단에는 더 이상 inline 슬롯이 없으므로 기본 빈 줄로 복원.
        core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"treatAsChar":false}"#)
            .expect("reverse toggle");
        let para = &core.document.sections[0].paragraphs[0];
        assert_eq!(para.line_segs.len(), 1);
        assert_eq!(
            para.line_segs[0].line_height, 1000,
            "남은 TAC 개체가 없으면 기본 빈 줄 높이로 복원"
        );
        assert_eq!(
            para.line_segs[0].baseline_distance, 850,
            "기본 빈 줄 기준선으로 복원"
        );
        let pic = match &para.controls[ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!(),
        };
        assert!(!pic.common.treat_as_char, "tac 비트는 false 로 토글");
    }

    // ─── 빈 line_segs paragraph 의 토글 — line_seg 신설 ────────────────
    #[test]
    fn tac_toggle_with_empty_line_segs_creates_new_seg() {
        let mut core = make_test_core();
        let pic_h = 7000u32;
        let ctrl_idx = {
            let para = &mut core.document.sections[0].paragraphs[0];
            para.line_segs.clear(); // 빈 line_segs 강제
            push_body_floating_picture(para, 7000, pic_h, 1000, 1000, 1)
        };
        core.set_picture_properties_native(0, 0, ctrl_idx, r#"{"treatAsChar":true}"#)
            .expect("migration");

        let para = &core.document.sections[0].paragraphs[0];
        assert!(
            !para.line_segs.is_empty(),
            "빈 line_segs 였다면 신설되어야 한다"
        );
        let seg = &para.line_segs[0];
        assert_eq!(seg.line_height, pic_h as i32);
        assert_eq!(seg.text_height, pic_h as i32);
        assert_eq!(seg.baseline_distance, expected_baseline(pic_h as i32));
    }

    // LineSeg 빈 케이스 직접 검증용 (별도 helper 미사용 check)
    #[test]
    #[allow(dead_code)]
    fn _lineseg_default_for_test() {
        let seg = LineSeg::default();
        assert_eq!(seg.line_height, 0);
    }

    // ═══════════════════════════════════════════════════════════════════
    //  통합 검증 (Stage 2): 한컴 산출물 정합
    //
    //  samples/tac-verify/scenario-{a,b,c,d}-before.hwp 를 rhwp 가 파싱한 후
    //  set_picture_properties_native 로 tac false→true 토글한 결과가
    //  scenario-{a,b,c,d}-after.hwp 의 model 과 dump 동치인지 검증한다.
    //  v2 fix 가 만든 model 이 한컴이 만든 model 과 양방향 정합임을 보장.
    // ═══════════════════════════════════════════════════════════════════

    /// 양방향 정합 검증의 공통 단언 — paragraph 0.0 의 picture / line_segs 비교.
    fn assert_toggle_matches_hancom(scenario: &str) {
        let before_bytes =
            std::fs::read(format!("samples/tac-verify/scenario-{scenario}-before.hwp"))
                .expect("read before.hwp");
        let after_bytes =
            std::fs::read(format!("samples/tac-verify/scenario-{scenario}-after.hwp"))
                .expect("read after.hwp");

        let before_doc = crate::parser::parse_hwp(&before_bytes).expect("parse before");
        let after_doc = crate::parser::parse_hwp(&after_bytes).expect("parse after");

        let mut core = DocumentCore::new_empty();
        core.set_document(before_doc);

        // picture 위치 찾기 (paragraph 0.0 의 첫 Picture control)
        let pic_ctrl_idx = core.document.sections[0].paragraphs[0]
            .controls
            .iter()
            .position(|c| matches!(c, Control::Picture(_)))
            .unwrap_or_else(|| panic!("scenario-{scenario}-before: no Picture control"));

        core.set_picture_properties_native(0, 0, pic_ctrl_idx, r#"{"treatAsChar":true}"#)
            .expect("toggle");

        // 토글된 picture
        let toggled_para = &core.document.sections[0].paragraphs[0];
        let toggled_pic = match &toggled_para.controls[pic_ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!("not Picture after toggle"),
        };

        // 한컴 after 의 picture
        let after_para = &after_doc.sections[0].paragraphs[0];
        let after_pic_ctrl_idx = after_para
            .controls
            .iter()
            .position(|c| matches!(c, Control::Picture(_)))
            .unwrap_or_else(|| panic!("scenario-{scenario}-after: no Picture control"));
        let after_pic = match &after_para.controls[after_pic_ctrl_idx] {
            Control::Picture(p) => p.as_ref(),
            _ => panic!(),
        };

        // (a) picture 4 필드 비교
        assert_eq!(
            toggled_pic.common.treat_as_char, after_pic.common.treat_as_char,
            "scenario-{scenario}: treat_as_char mismatch"
        );
        assert_eq!(
            toggled_pic.common.horizontal_offset, after_pic.common.horizontal_offset,
            "scenario-{scenario}: horizontal_offset mismatch"
        );
        assert_eq!(
            toggled_pic.common.vertical_offset, after_pic.common.vertical_offset,
            "scenario-{scenario}: vertical_offset mismatch"
        );
        assert_eq!(
            toggled_pic.common.horz_rel_to as u8, after_pic.common.horz_rel_to as u8,
            "scenario-{scenario}: horz_rel_to mismatch"
        );
        assert_eq!(
            toggled_pic.common.vert_rel_to as u8, after_pic.common.vert_rel_to as u8,
            "scenario-{scenario}: vert_rel_to mismatch"
        );

        // (b) line_segs[0] 비교
        let toggled_seg = &toggled_para.line_segs[0];
        let after_seg = &after_para.line_segs[0];
        assert_eq!(
            toggled_seg.line_height, after_seg.line_height,
            "scenario-{scenario}: line_height mismatch"
        );
        assert_eq!(
            toggled_seg.text_height, after_seg.text_height,
            "scenario-{scenario}: text_height mismatch"
        );
        assert_eq!(
            toggled_seg.baseline_distance, after_seg.baseline_distance,
            "scenario-{scenario}: baseline_distance mismatch (round(lh*0.85) 정합)"
        );

        // (c) paragraph 수 / picture 위치 불변
        assert_eq!(
            core.document.sections[0].paragraphs.len(),
            after_doc.sections[0].paragraphs.len(),
            "scenario-{scenario}: paragraph count mismatch"
        );
        assert_eq!(
            pic_ctrl_idx, after_pic_ctrl_idx,
            "scenario-{scenario}: picture control_idx mismatch"
        );

        // (d) paragraph.text 불변
        assert_eq!(
            toggled_para.text, after_para.text,
            "scenario-{scenario}: paragraph.text mismatch"
        );
    }

    #[test]
    fn integration_tac_toggle_matches_hancom_scenario_a() {
        assert_toggle_matches_hancom("a");
    }

    #[test]
    fn integration_tac_toggle_matches_hancom_scenario_b() {
        assert_toggle_matches_hancom("b");
    }

    #[test]
    fn integration_tac_toggle_matches_hancom_scenario_c() {
        assert_toggle_matches_hancom("c");
    }

    #[test]
    fn integration_tac_toggle_matches_hancom_scenario_d() {
        assert_toggle_matches_hancom("d");
    }
}

#[cfg(test)]
mod issue_1280_textbox_creation_tests {
    //! Issue #1280: rhwp-studio가 삽입한 글상자가 text_box 없는 Rectangle로 생성되어
    //! 커서 진입·타이핑·붙여넣기가 모두 실패하던 결함.
    //!
    //! 근본 결함은 프런트(`input-handler.ts`)가 `shapeType: 'rectangle'`을 전달한 것이고,
    //! 백엔드 `create_shape_control_native`는 `shape_type == "textbox"`일 때 text_box(내부 문단)를
    //! 정상 구성한다. 본 테스트는 그 백엔드 계약(글상자=text_box 있음, 사각형=없음)을 고정하여
    //! 프런트 수정과 함께 회귀를 막는다.

    use super::*;
    use crate::model::document::{Document, Section, SectionDef};
    use crate::model::page::PageDef;

    fn make_test_core() -> DocumentCore {
        let mut doc = Document::default();
        doc.sections.push(Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 59528,
                    height: 84188,
                    margin_left: 8504,
                    margin_right: 8504,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            paragraphs: vec![Paragraph::default()],
            trailing_lists: None,
            raw_stream: None,
            raw_provenance: None,
        });
        let mut core = DocumentCore::new_empty();
        core.set_document(doc);
        core
    }

    fn parse_idx(res: &str, key: &str) -> usize {
        res.split(&format!("\"{}\":", key))
            .nth(1)
            .and_then(|s| s.split(|c: char| !c.is_ascii_digit()).next())
            .and_then(|s| s.parse().ok())
            .unwrap_or_else(|| panic!("missing {key} in {res}"))
    }

    fn minimal_png() -> Vec<u8> {
        vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x00, 0x00, 0x00,
            0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ]
    }

    /// 도형 생성 후 (para_idx, ctrl_idx) 반환. 글상자는 한컴 기본값과 동일하게 treat_as_char=true.
    fn create_shape(core: &mut DocumentCore, shape_type: &str) -> (usize, usize) {
        let treat_as_char = shape_type == "textbox";
        // 인자: section_idx, para_idx, char_offset, width, height, horz_offset, vert_offset,
        // treat_as_char, text_wrap_str, shape_type, line_flip_x, line_flip_y, polygon_points
        let res = core
            .create_shape_control_native(
                0,
                0,
                0,
                21600,
                7200,
                0,
                0,
                treat_as_char,
                "TopAndBottom",
                shape_type,
                false,
                false,
                &[],
            )
            .unwrap_or_else(|e| panic!("create {shape_type} failed: {e:?}"));
        (parse_idx(&res, "paraIdx"), parse_idx(&res, "controlIdx"))
    }

    fn textbox_of<'a>(
        core: &'a DocumentCore,
        para_idx: usize,
        ctrl_idx: usize,
    ) -> Option<&'a crate::model::shape::TextBox> {
        match &core.document.sections[0].paragraphs[para_idx].controls[ctrl_idx] {
            Control::Shape(s) => crate::document_core::helpers::get_textbox_from_shape(s.as_ref()),
            other => panic!("expected Control::Shape, got {other:?}"),
        }
    }

    fn common_of<'a>(
        core: &'a DocumentCore,
        para_idx: usize,
        ctrl_idx: usize,
    ) -> &'a crate::model::shape::CommonObjAttr {
        match &core.document.sections[0].paragraphs[para_idx].controls[ctrl_idx] {
            Control::Shape(s) => s.common(),
            other => panic!("expected Control::Shape, got {other:?}"),
        }
    }

    /// 글상자를 직접 인자로 생성(treat_as_char/text_wrap 명시). (para_idx, ctrl_idx) 반환.
    fn create_textbox_with(
        core: &mut DocumentCore,
        treat_as_char: bool,
        text_wrap: &str,
    ) -> (usize, usize) {
        let res = core
            .create_shape_control_native(
                0,
                0,
                0,
                21600,
                7200,
                1000,
                2000,
                treat_as_char,
                text_wrap,
                "textbox",
                false,
                false,
                &[],
            )
            .unwrap_or_else(|e| panic!("create textbox failed: {e:?}"));
        (parse_idx(&res, "paraIdx"), parse_idx(&res, "controlIdx"))
    }

    /// [Task #1280 v2] 삽입 글상자를 floating(treat_as_char=false)+InFrontOfText 로 만들면
    /// 한컴 정답값(Paper/Paper/글앞으로)으로 생성되고 text_box 는 그대로 유지된다.
    /// 권위 샘플 samples/textbox-under-image.hwp 실측 정합.
    #[test]
    fn create_floating_textbox_is_in_front_paper() {
        use crate::model::shape::{HorzRelTo, TextWrap, VertRelTo};
        let mut core = make_test_core();
        let (para, ctrl) = create_textbox_with(&mut core, false, "InFrontOfText");

        // text_box 유지 (글상자 기능 보존 — floating 에서도)
        assert!(
            textbox_of(&core, para, ctrl).is_some(),
            "floating 글상자도 text_box 를 가져야 한다"
        );

        let c = common_of(&core, para, ctrl);
        assert!(!c.treat_as_char, "floating: treat_as_char=false");
        assert_eq!(
            c.text_wrap,
            TextWrap::InFrontOfText,
            "글앞으로(InFrontOfText)"
        );
        assert_eq!(c.vert_rel_to, VertRelTo::Paper, "vert_rel_to=Paper");
        assert_eq!(c.horz_rel_to, HorzRelTo::Paper, "horz_rel_to=Paper");
        // 직렬화 attr 비트 정합 (serializer 는 common.attr!=0 이면 그대로 사용).
        assert_eq!(c.attr & 0x01, 0, "attr bit0(treat_as_char)=0");
        assert_eq!((c.attr >> 3) & 0x03, 0, "attr bit3-4(vert_rel_to)=Paper(0)");
        assert_eq!((c.attr >> 8) & 0x03, 0, "attr bit8-9(horz_rel_to)=Paper(0)");
        assert_eq!(
            (c.attr >> 21) & 0x07,
            3,
            "attr bit21-23(text_wrap)=InFrontOfText(3)"
        );
    }

    /// inline 글상자(treat_as_char=true)는 #1280 본편 배치(Para/Column)를 그대로 보존한다(회귀 가드).
    #[test]
    fn create_inline_textbox_preserves_para_column() {
        use crate::model::shape::{HorzRelTo, VertRelTo};
        let mut core = make_test_core();
        let (para, ctrl) = create_textbox_with(&mut core, true, "Square");
        let c = common_of(&core, para, ctrl);
        assert!(c.treat_as_char, "inline: treat_as_char=true");
        assert_eq!(c.vert_rel_to, VertRelTo::Para, "inline vert_rel_to=Para");
        assert_eq!(
            c.horz_rel_to,
            HorzRelTo::Column,
            "inline horz_rel_to=Column"
        );
    }

    /// floating 글상자에도 텍스트 입력이 정상 동작(#1280 본편 회귀 없음).
    #[test]
    fn insert_text_into_floating_textbox() {
        let mut core = make_test_core();
        let (para, ctrl) = create_textbox_with(&mut core, false, "InFrontOfText");
        core.insert_text_in_cell_native(0, para, ctrl, 0, 0, 0, "플로팅")
            .expect("floating 글상자 텍스트 입력 성공");
        let tb = textbox_of(&core, para, ctrl).expect("text_box 존재");
        assert_eq!(
            tb.paragraphs[0].text, "플로팅",
            "floating 글상자 내부 텍스트 보존"
        );
    }

    /// 글상자 안에서 이미지 배치 영역을 드래그한 경우, 그림은 body sibling 이 아니라
    /// text_box 내부 paragraph 의 Picture control 로 들어가야 한다.
    #[test]
    fn insert_picture_into_textbox_uses_textbox_paragraph_control() {
        use crate::model::shape::{HorzRelTo, TextWrap, VertRelTo};

        let mut core = make_test_core();
        let (para, ctrl) = create_textbox_with(&mut core, false, "InFrontOfText");
        let body_control_count_before = core.document.sections[0].paragraphs[para].controls.len();
        let cell_path = vec![(ctrl, 0, 0)];
        let image = minimal_png();

        core.insert_picture_native(
            0,
            para,
            0,
            &cell_path,
            &image,
            5000,
            4000,
            1,
            1,
            "png",
            "textbox picture",
            Some(750),
            Some(1500),
        )
        .expect("글상자 내부 picture 삽입 성공");

        let body = &core.document.sections[0].paragraphs[para];
        assert_eq!(
            body.controls.len(),
            body_control_count_before,
            "글상자 내부 삽입은 body sibling control 을 추가하면 안 된다"
        );

        let tb = textbox_of(&core, para, ctrl).expect("글상자 text_box 존재");
        let picture = tb.paragraphs[0]
            .controls
            .iter()
            .find_map(|c| match c {
                Control::Picture(p) => Some(p.as_ref()),
                _ => None,
            })
            .expect("글상자 내부 문단에 Picture control 이 있어야 한다");

        assert!(!picture.common.treat_as_char);
        assert_eq!(picture.common.horz_rel_to, HorzRelTo::Para);
        assert_eq!(picture.common.vert_rel_to, VertRelTo::Para);
        assert_eq!(picture.common.text_wrap, TextWrap::Square);
        assert_eq!(picture.common.horizontal_offset, 750);
        assert_eq!(picture.common.vertical_offset, 1500);
        assert_eq!(picture.common.width, 5000);
        assert_eq!(picture.common.height, 4000);
    }

    #[test]
    fn create_textbox_has_textbox() {
        let mut core = make_test_core();
        let (para, ctrl) = create_shape(&mut core, "textbox");
        assert!(
            textbox_of(&core, para, ctrl).is_some(),
            "글상자(shape_type=textbox)는 text_box를 가져야 한다 (#1280)"
        );
    }

    #[test]
    fn create_rectangle_has_no_textbox() {
        let mut core = make_test_core();
        let (para, ctrl) = create_shape(&mut core, "rectangle");
        assert!(
            textbox_of(&core, para, ctrl).is_none(),
            "일반 사각형(shape_type=rectangle)은 text_box가 없어야 한다 (글상자/사각형 경로 분리)"
        );
    }

    #[test]
    fn insert_text_into_created_textbox() {
        let mut core = make_test_core();
        let (para, ctrl) = create_shape(&mut core, "textbox");

        // 글상자 내부(cell_idx=0 무시, cell_para_idx=0, char_offset=0)에 텍스트 삽입.
        // 수정 전 프런트 경로에서는 text_box가 없어 "지정된 Shape 컨트롤에 텍스트 박스가 없습니다"로 실패했다.
        core.insert_text_in_cell_native(0, para, ctrl, 0, 0, 0, "테스트")
            .expect("글상자에 텍스트 입력이 성공해야 한다 (#1280)");

        let tb = textbox_of(&core, para, ctrl).expect("글상자 text_box 존재");
        assert_eq!(
            tb.paragraphs[0].text, "테스트",
            "글상자 내부 첫 문단에 입력 텍스트가 보존되어야 한다"
        );
    }

    /// #1280 이슈가 기대 동작에 명시한 "글상자 안 붙여넣기"를 실측한다.
    /// 본문 텍스트를 copy_selection 으로 복사한 뒤 글상자 안에 paste_internal_in_cell 로 붙여넣는다.
    /// 수정 전(text_box 없는 Rectangle)이면 이 경로가 "글상자 없음"(clipboard.rs:512)으로 실패한다.
    ///
    /// 이미지/컨트롤 붙여넣기는 merge_from 이 controls 를 병합하지 않아 조용히 누락되던
    /// 별개 결함(#1323)이 있었으며, merge_from 보강으로 해소되었다.
    /// 회귀 테스트는 `paste_picture_into_textbox` 참고.
    #[test]
    fn paste_text_into_textbox() {
        let mut core = make_test_core();

        // 1. 본문에 텍스트 입력 후 선택 영역 복사 → 내부 클립보드에 텍스트 적재(controls 없음)
        core.insert_text_native(0, 0, 0, "복사원본")
            .expect("본문 텍스트 입력");
        core.copy_selection_native(0, 0, 0, 0, 4)
            .expect("본문 텍스트 복사");

        // 2. 글상자 생성
        let (tb_para, tb_ctrl) = create_shape(&mut core, "textbox");

        // 3. 글상자 안에 붙여넣기 (cell_idx=0, cell_para_idx=0, char_offset=0)
        core.paste_internal_in_cell_native(0, tb_para, tb_ctrl, 0, 0, 0)
            .expect("글상자에 붙여넣기가 성공해야 한다 (#1280; 수정 전엔 \"글상자 없음\")");

        // 4. 글상자 내부 첫 문단에 붙여넣은 텍스트가 들어갔는지 확인
        let tb = textbox_of(&core, tb_para, tb_ctrl).expect("글상자 text_box 존재");
        assert!(
            tb.paragraphs.iter().any(|p| p.text.contains("복사원본")),
            "붙여넣기 후 글상자 내부 문단에 복사한 텍스트가 있어야 한다"
        );
    }

    /// #1323: 글상자 안 이미지(그림 컨트롤) 붙여넣기 회귀 테스트.
    /// 본문 그림을 copy_control 로 복사한 뒤 글상자 안에 paste_internal_in_cell 로
    /// 붙여넣는다. merge_from 이 controls 를 병합하지 않던 수정 전에는 그림이
    /// 에러 없이 조용히 누락되었다.
    #[test]
    fn paste_picture_into_textbox() {
        let mut core = make_test_core();

        // 1. 본문에 그림 삽입 (BinData 등록 포함)
        let res = core
            .insert_picture_native(
                0,
                0,
                0,
                &[],
                &minimal_png(),
                5000,
                5000,
                1,
                1,
                "png",
                "",
                None,
                None,
            )
            .expect("본문 그림 삽입");
        let pic_para = parse_idx(&res, "paraIdx");
        let pic_ctrl = parse_idx(&res, "controlIdx");

        // 2. 그림 복사 → 내부 클립보드
        core.copy_control_native(0, pic_para, &[], pic_ctrl)
            .expect("그림 복사");

        // 3. 글상자 생성 + 안에 붙여넣기 (cell_idx=0 무시, cell_para_idx=0, char_offset=0)
        let (tb_para, tb_ctrl) = create_shape(&mut core, "textbox");
        core.paste_internal_in_cell_native(0, tb_para, tb_ctrl, 0, 0, 0)
            .expect("글상자에 그림 붙여넣기");

        // 4. 글상자 내부 문단에 그림 컨트롤 보존 확인
        let tb = textbox_of(&core, tb_para, tb_ctrl).expect("글상자 text_box 존재");
        let pic_count: usize = tb
            .paragraphs
            .iter()
            .map(|p| {
                p.controls
                    .iter()
                    .filter(|c| matches!(c, Control::Picture(_)))
                    .count()
            })
            .sum();
        assert_eq!(
            pic_count, 1,
            "글상자 안에 붙여넣은 그림 컨트롤이 보존되어야 한다 (#1323)"
        );
    }
}

#[cfg(test)]
mod bindata_storage_id_collision_tests {
    //! Issue #2038: BinData storage id 채번 충돌 — 순번(len+1) 채번은 storage id 에 구멍이
    //! 있는 문서에서 기존 id 와 충돌해, 저장 시 같은 이름(BIN%04X)의 스트림이
    //! 겹쳐 이미지가 뒤바뀌거나 소실된다. storage id 는 최댓값+1 로 채번하되
    //! 위치 의미인 `ImageAttr.bin_data_id` 는 순번을 유지해야 한다.

    use super::*;
    use crate::model::bin_data::{
        BinData, BinDataCompression, BinDataContent, BinDataStatus, BinDataType,
    };
    use std::collections::HashSet;

    const EXISTING_IMAGE: &[u8] = &[0xAA, 0xBB, 0xCC];

    fn minimal_png() -> Vec<u8> {
        vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x00, 0x00, 0x00,
            0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ]
    }

    /// 실제 문서를 로드한 뒤 storage id 2 만 존재하는 구멍(1 없음)을 주입한다.
    /// 구채번(len+1 = 2)이라면 기존 id 2 와 충돌하는 구성.
    fn make_core_with_storage_hole() -> DocumentCore {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("samples/basic/english.hwp");
        let bytes = std::fs::read(&path).expect("read english.hwp");
        let mut core = DocumentCore::from_bytes(&bytes).expect("load english.hwp");
        assert!(
            core.document.bin_data_content.is_empty(),
            "전제: english.hwp 에는 BinData 가 없어야 함"
        );
        core.document.bin_data_content.push(BinDataContent {
            id: 2,
            data: EXISTING_IMAGE.to_vec().into(),
            extension: "png".to_string(),
        });
        core.document.doc_info.bin_data_list.push(BinData {
            raw_data: None,
            attr: 0x0101,
            data_type: BinDataType::Embedding,
            compression: BinDataCompression::Default,
            status: BinDataStatus::Success,
            abs_path: None,
            rel_path: None,
            storage_id: 2,
            extension: Some("png".to_string()),
        });
        core
    }

    #[test]
    fn insert_picture_storage_id_skips_existing_ids() {
        let mut core = make_core_with_storage_hole();
        core.insert_picture_native(
            0,
            0,
            0,
            &[],
            &minimal_png(),
            9000,
            6000,
            1,
            1,
            "png",
            "",
            None,
            None,
        )
        .expect("insert_picture_native");

        let content_ids: Vec<u16> = core
            .document
            .bin_data_content
            .iter()
            .map(|c| c.id)
            .collect();
        let unique: HashSet<u16> = content_ids.iter().copied().collect();
        assert_eq!(
            unique.len(),
            content_ids.len(),
            "BinDataContent.id 가 중복되면 저장 시 스트림 이름이 충돌한다: {content_ids:?}"
        );
        let storage_ids: Vec<u16> = core
            .document
            .doc_info
            .bin_data_list
            .iter()
            .map(|b| b.storage_id)
            .collect();
        let unique_storage: HashSet<u16> = storage_ids.iter().copied().collect();
        assert_eq!(
            unique_storage.len(),
            storage_ids.len(),
            "BinData.storage_id 중복: {storage_ids:?}"
        );

        // bin_data_id 는 위치(1-based 순번) 의미 유지 — 신규 그림은 2번째 content
        let new_bin_id = core.document.sections[0]
            .paragraphs
            .iter()
            .flat_map(|p| p.controls.iter())
            .find_map(|c| match c {
                Control::Picture(pic) => Some(pic.image_attr.bin_data_id),
                _ => None,
            })
            .expect("삽입된 그림 컨트롤");
        assert_eq!(
            new_bin_id, 2,
            "bin_data_id 는 content 배열 1-based 순번이어야 함"
        );
        let by_position = &core.document.bin_data_content[(new_bin_id - 1) as usize];
        assert_eq!(
            by_position.data.load(),
            minimal_png(),
            "위치 기반 조회로 신규 그림 데이터가 나와야 함"
        );
        // 기존 이미지 데이터 불변
        assert_eq!(
            core.document.bin_data_content[0].data.load(),
            EXISTING_IMAGE
        );
    }

    #[test]
    fn insert_into_storage_hole_doc_survives_hwp_save_roundtrip() {
        let mut core = make_core_with_storage_hole();
        core.insert_picture_native(
            0,
            0,
            0,
            &[],
            &minimal_png(),
            9000,
            6000,
            1,
            1,
            "png",
            "",
            None,
            None,
        )
        .expect("insert_picture_native");

        let saved = core.export_hwp_with_adapter().expect("export_hwp");
        let reloaded = DocumentCore::from_bytes(&saved).expect("재로드");
        let datas: Vec<Vec<u8>> = reloaded
            .document()
            .bin_data_content
            .iter()
            .map(|c| c.data.load())
            .collect();
        assert!(
            datas.iter().any(|d| &d[..] == EXISTING_IMAGE),
            "저장 왕복 후 기존 이미지가 소실됨 (스트림 이름 충돌): {:?}",
            reloaded
                .document()
                .bin_data_content
                .iter()
                .map(|c| (c.id, c.data.len()))
                .collect::<Vec<_>>()
        );
        assert!(
            datas.iter().any(|d| &d[..] == minimal_png().as_slice()),
            "저장 왕복 후 신규 이미지가 소실됨"
        );
    }
}

#[cfg(test)]
mod issue_4347_insert_leaves_coordinate_trace {
    //! [#4347] 그림 삽입이 `char_offsets` 에 갭을 안 남겨 개체 좌표가 문단 끝으로 떨어졌다.
    //!
    //! 파서는 확장 컨트롤을 만나면 8 코드 유닛을 건너뛰고 **보이는 글자를 안 남긴다**. 그래서
    //! 컨트롤의 자리는 `control_text_positions()` 가 `char_offsets` 의 **갭**으로 되짚는다.
    //! 삽입 경로가 그 갭을 만들지 않으면 그 컨트롤은 자리를 잃고 문단 끝 폴백으로 떨어진다.
    //! 수식·각주·새 번호 경로는 이미 `shift_for_inline_control_insert` 로 갭을 만든다.

    use super::*;
    use crate::model::document::{Document, Section};
    use crate::model::paragraph::Paragraph;

    fn core_with_two_leading_controls() -> DocumentCore {
        // 앞머리에 확장 컨트롤 둘(구역·단 정의처럼 16칸)이 있고 그 뒤로 글자 열이 오는 문단.
        let mut para = Paragraph {
            text: "0123456789".to_string(),
            char_offsets: (16..26).collect(),
            char_count: 27,
            ..Default::default()
        };
        para.controls.push(Control::SectionDef(Default::default()));
        para.controls.push(Control::ColumnDef(Default::default()));
        para.ctrl_data_records.push(None);
        para.ctrl_data_records.push(None);
        let mut doc = Document::default();
        doc.sections.push(Section {
            paragraphs: vec![para],
            ..Default::default()
        });
        let mut core = DocumentCore::new_empty();
        core.set_document(doc);
        core
    }

    fn png() -> Vec<u8> {
        vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1F, 0x15, 0xC4, 0x89,
        ]
    }

    /// 글상자 문단은 **글자를 담는다** — 표 문단(글자 없음)과 달리 갭이 없으면 자리가 어긋난다.
    #[test]
    fn inserted_picture_in_a_textbox_keeps_its_place_too() {
        let mut core = DocumentCore::new_empty();
        let mut doc = Document::default();
        doc.sections.push(Section {
            paragraphs: vec![Paragraph::default()],
            ..Default::default()
        });
        core.set_document(doc);
        // 글상자를 만들고 그 안에 글자 일곱을 넣는다.
        let made = core
            .create_shape_control_native(
                0,
                0,
                0,
                20000,
                10000,
                0,
                0,
                true,
                "square",
                "textbox",
                false,
                false,
                &[],
            )
            .expect("글상자");
        let ctrl_idx =
            crate::document_core::helpers::json_u32(&made, "controlIdx").unwrap() as usize;
        core.insert_text_in_cell_native(0, 0, ctrl_idx, 0, 0, 0, "가나다라마바사")
            .expect("글상자에 글");

        core.insert_picture_native(
            0,
            0,
            3,
            &[(ctrl_idx, 0, 0)],
            &png(),
            100,
            100,
            1,
            1,
            "png",
            "",
            None,
            None,
        )
        .expect("글상자 안 그림");

        let shape = match &core.document.sections[0].paragraphs[0].controls[ctrl_idx] {
            Control::Shape(s) => s,
            other => panic!("글상자가 아니다: {:?}", other),
        };
        let tb = shape
            .drawing()
            .and_then(|d| d.text_box.as_ref())
            .expect("글상자 안");
        let para = &tb.paragraphs[0];
        assert_eq!(
            para.char_offsets[2], 2,
            "넣은 자리 앞 글자는 그대로여야 한다"
        );
        assert_eq!(
            para.char_offsets[3], 11,
            "넣은 자리 뒤 글자는 컨트롤 몫 8칸만큼 밀려야 한다"
        );
        assert_eq!(
            para.control_text_positions().first().copied(),
            Some(3),
            "그림은 넣은 글자 자리에 있어야 한다"
        );
    }

    #[test]
    fn inserted_picture_keeps_its_place_not_the_paragraph_end() {
        let mut core = core_with_two_leading_controls();
        core.insert_picture_native(0, 0, 4, &[], &png(), 100, 100, 1, 1, "png", "", None, None)
            .expect("그림 삽입");

        let para = &core.document.sections[0].paragraphs[0];
        // 넣은 자리 뒤 글자들은 8칸 밀려야 한다 — 그 갭이 곧 그림의 자리다.
        assert_eq!(
            para.char_offsets[3], 19,
            "넣은 자리 앞 글자는 그대로여야 한다"
        );
        assert_eq!(
            para.char_offsets[4], 28,
            "넣은 자리 뒤 글자는 컨트롤 몫 8칸만큼 밀려야 한다"
        );
        assert_eq!(para.char_count, 35, "문단 길이도 8칸 늘어야 한다");

        // 그 갭 덕분에 컨트롤 자리가 되짚어진다 — 문단 끝이 아니라 넣은 자리다.
        let positions = para.control_text_positions();
        assert_eq!(
            positions.len(),
            3,
            "구역 정의·단 정의·그림 셋의 자리가 나와야 한다"
        );
        assert_eq!(positions[2], 4, "그림은 넣은 글자 자리에 있어야 한다");
    }
}