libvisio-rs 0.2.1

A Rust library for parsing Microsoft Visio files (.vsdx and .vsd) and converting to SVG
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
//! Shape → SVG conversion.
//!
//! This module contains the complete SVG rendering pipeline, ported from
//! the Python libvisio-ng. It handles geometry paths, text, gradients,
//! shadows, arrows, fills, hatching patterns, connectors, and all the visual features.

use crate::model::*;
use std::collections::{HashMap, HashSet};

/// Inches to SVG pixels.
const INCH_TO_PX: f64 = 72.0;

/// Visio color index table.
static VISIO_COLORS: &[(i32, &str)] = &[
    (0, "#000000"),
    (1, "#FFFFFF"),
    (2, "#FF0000"),
    (3, "#00FF00"),
    (4, "#0000FF"),
    (5, "#FFFF00"),
    (6, "#FF00FF"),
    (7, "#00FFFF"),
    (8, "#800000"),
    (9, "#008000"),
    (10, "#000080"),
    (11, "#808000"),
    (12, "#800080"),
    (13, "#008080"),
    (14, "#C0C0C0"),
    (15, "#808080"),
    (16, "#993366"),
    (17, "#333399"),
    (18, "#333333"),
    (19, "#003300"),
    (20, "#003366"),
    (21, "#993300"),
    (22, "#993366"),
    (23, "#333399"),
    (24, "#E6E6E6"),
];

/// Complete Visio line pattern dash arrays (all 23 patterns).
static LINE_PATTERNS: &[(i32, &str)] = &[
    (0, "none"),           // No line
    (1, ""),               // Solid
    (2, "4,3"),            // Dash
    (3, "1,3"),            // Dot
    (4, "4,3,1,3"),        // Dash-dot
    (5, "4,3,1,3,1,3"),   // Dash-dot-dot
    (6, "8,3"),            // Long dash
    (7, "1,1"),            // Dense dot
    (8, "8,3,1,3"),        // Long dash-dot
    (9, "8,3,1,3,1,3"),   // Long dash-dot-dot
    (10, "12,6"),          // Extra-long dash
    (11, "12,3,1,3"),     // Extra-long dash-dot
    (12, "12,3,1,3,1,3"), // Extra-long dash-dot-dot
    (13, "2,2"),           // Short dash
    (14, "2,2,6,2"),       // Short dash-long dash
    (15, "2,2,6,2,6,2"),   // Short dash-long dash-long dash
    (16, "6,3,6,3"),       // Dash-dash
    (17, "1,1,6,1"),       // Dot-dash (tight)
    (18, "10,2"),          // Heavy dash
    (19, "1,3,6,3"),       // Dot-long dash
    (20, "1,3,6,3,6,3"),   // Dot-long dash-long dash
    (21, "1,3,1,3,6,3"),   // Dot-dot-long dash
    (22, "6,1"),           // Tight dash
    (23, "1,1,1,1,6,1"),   // Tight dot-dot-dash
];

/// Arrow size scale factors.
static ARROW_SIZES: &[(i32, f64)] = &[
    (0, 0.6),
    (1, 0.8),
    (2, 1.0),
    (3, 1.2),
    (4, 1.6),
    (5, 2.0),
    (6, 2.5),
];

/// Gradient angle mapping for fill patterns 25-40.
static PATTERN_ANGLES: &[(i32, f64)] = &[
    (25, 270.0), (26, 0.0), (27, 90.0), (28, 180.0),
    (33, 315.0), (34, 45.0), (35, 135.0), (36, 225.0),
];

/// QuickStyle fill color to theme color name mapping.
static QUICKSTYLE_FILL_MAP: &[(i32, &str)] = &[
    (0, "dk1"), (1, "lt1"), (2, "accent1"), (3, "accent2"),
    (4, "accent3"), (5, "accent4"), (6, "accent5"), (7, "accent6"),
    (100, "dk1"), (101, "lt1"), (102, "accent1"), (103, "accent2"),
    (104, "accent3"), (105, "accent4"), (106, "accent5"), (107, "accent6"),
];

fn arrow_size(idx: i32) -> f64 {
    ARROW_SIZES
        .iter()
        .find(|&&(i, _)| i == idx)
        .map(|&(_, s)| s)
        .unwrap_or(1.0)
}

fn pattern_angle(idx: i32) -> f64 {
    PATTERN_ANGLES
        .iter()
        .find(|&&(i, _)| i == idx)
        .map(|&(_, a)| a)
        .unwrap_or(0.0)
}

/// Resolve a QuickStyle fill color index to a theme color.
pub fn resolve_quickstyle_color(idx: i32, theme_colors: &HashMap<String, String>) -> String {
    let name = QUICKSTYLE_FILL_MAP
        .iter()
        .find(|&&(i, _)| i == idx)
        .map(|&(_, n)| n)
        .unwrap_or("accent1");
    theme_colors.get(name).cloned().unwrap_or_default()
}

/// Resolve a Visio color value to SVG hex.
pub fn resolve_color(val: &str, theme_colors: &HashMap<String, String>) -> String {
    let val = val.trim();
    if val.is_empty() {
        return String::new();
    }

    // THEMEVAL / THEMEGUARD
    let upper = val.to_uppercase();
    if upper.contains("THEMEVAL") || upper.contains("THEMEGUARD") {
        // Unwrap nested THEMEGUARD(THEMEVAL(...))
        let inner = unwrap_themeguard(val);
        if let Some(key) = extract_themeval_key(&inner) {
            if let Some(color) = theme_colors.get(&key) {
                return color.clone();
            }
        }
        return String::new();
    }

    if val == "Inh" || val.starts_with('=') || upper.contains("THEME") {
        return String::new();
    }

    // #RRGGBB
    if val.starts_with('#') {
        return val.to_string();
    }

    // RGB(r,g,b)
    if let Some(color) = parse_rgb_func(val) {
        return color;
    }

    // HSL(h,s,l)
    if let Some(color) = parse_hsl_func(val) {
        return color;
    }

    // Numeric index
    if let Ok(idx) = val.parse::<f64>() {
        let i = idx as i32;
        if let Some(&(_, color)) = VISIO_COLORS.iter().find(|&&(ci, _)| ci == i) {
            return color.to_string();
        }
    }

    String::new()
}

/// Unwrap THEMEGUARD(expr) to get inner expression.
fn unwrap_themeguard(val: &str) -> String {
    let mut s = val.to_string();
    while s.to_uppercase().starts_with("THEMEGUARD(") && s.ends_with(')') {
        s = s[11..s.len() - 1].to_string();
    }
    s
}

fn extract_themeval_key(val: &str) -> Option<String> {
    let upper = val.to_uppercase();
    if let Some(start) = upper.find("THEMEVAL") {
        let rest = &val[start + 8..];
        if let Some(paren_start) = rest.find('(') {
            let inner = &rest[paren_start + 1..];
            // Try quoted key: THEMEVAL("accent1",0)
            if let Some(q_start) = inner.find('"') {
                if let Some(q_end) = inner[q_start + 1..].find('"') {
                    return Some(inner[q_start + 1..q_start + 1 + q_end].to_lowercase());
                }
            }
            // Try numeric: THEMEVAL(0)
            let num_str: String = inner.chars().take_while(|c| c.is_ascii_digit()).collect();
            if !num_str.is_empty() {
                return Some(num_str);
            }
        }
    }
    None
}

fn parse_rgb_func(val: &str) -> Option<String> {
    let upper = val.to_uppercase();
    if !upper.starts_with("RGB") {
        return None;
    }
    let inner = val.split('(').nth(1)?.split(')').next()?;
    let parts: Vec<&str> = inner.split(',').collect();
    if parts.len() != 3 {
        return None;
    }
    let r: u8 = parts[0].trim().parse().ok()?;
    let g: u8 = parts[1].trim().parse().ok()?;
    let b: u8 = parts[2].trim().parse().ok()?;
    Some(format!("#{:02X}{:02X}{:02X}", r, g, b))
}

fn parse_hsl_func(val: &str) -> Option<String> {
    let upper = val.to_uppercase();
    if !upper.starts_with("HSL") {
        return None;
    }
    let inner = val.split('(').nth(1)?.split(')').next()?;
    let parts: Vec<&str> = inner.split(',').collect();
    if parts.len() != 3 {
        return None;
    }
    let h: f64 = parts[0].trim().parse().ok()?;
    let s: f64 = parts[1].trim().parse().ok()?;
    let l: f64 = parts[2].trim().parse().ok()?;
    Some(hsl_to_rgb(h as i32, s as i32, l as i32))
}

fn hsl_to_rgb(h: i32, s: i32, l: i32) -> String {
    let hf = (h as f64 / 255.0) * 360.0;
    let sf = s as f64 / 255.0;
    let lf = l as f64 / 255.0;
    let (r, g, b) = if sf == 0.0 {
        (lf, lf, lf)
    } else {
        let q = if lf < 0.5 {
            lf * (1.0 + sf)
        } else {
            lf + sf - lf * sf
        };
        let p = 2.0 * lf - q;
        let hn = hf / 360.0;
        (
            hue2rgb(p, q, hn + 1.0 / 3.0),
            hue2rgb(p, q, hn),
            hue2rgb(p, q, hn - 1.0 / 3.0),
        )
    };
    format!(
        "#{:02X}{:02X}{:02X}",
        (r * 255.0) as u8,
        (g * 255.0) as u8,
        (b * 255.0) as u8
    )
}

fn hue2rgb(p: f64, q: f64, mut t: f64) -> f64 {
    if t < 0.0 {
        t += 1.0;
    }
    if t > 1.0 {
        t -= 1.0;
    }
    if t < 1.0 / 6.0 {
        return p + (q - p) * 6.0 * t;
    }
    if t < 0.5 {
        return q;
    }
    if t < 2.0 / 3.0 {
        return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
    }
    p
}

pub fn lighten_color(hex: &str, factor: f64) -> String {
    let hex = hex.trim().trim_start_matches('#');
    if hex.len() != 6 {
        return "#E8E8E8".to_string();
    }
    let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0) as f64;
    let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0) as f64;
    let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0) as f64;
    let r = (r + (255.0 - r) * factor) as u8;
    let g = (g + (255.0 - g) * factor) as u8;
    let b = (b + (255.0 - b) * factor) as u8;
    format!("#{:02X}{:02X}{:02X}", r, g, b)
}

pub fn is_dark_color(color: &str) -> bool {
    if color.is_empty() || color == "none" {
        return false;
    }
    let c = color.trim().trim_start_matches('#');
    if c.len() == 6 {
        if let (Ok(r), Ok(g), Ok(b)) = (
            u8::from_str_radix(&c[0..2], 16),
            u8::from_str_radix(&c[2..4], 16),
            u8::from_str_radix(&c[4..6], 16),
        ) {
            let lum = (0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64) / 255.0;
            return lum < 0.4;
        }
    }
    false
}

fn escape_xml(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

fn get_dash_array(pattern: i32, weight: f64) -> String {
    if pattern == 0 {
        return "none".to_string();
    }
    let p = LINE_PATTERNS
        .iter()
        .find(|&&(i, _)| i == pattern)
        .map(|&(_, s)| s)
        .unwrap_or("");
    if p.is_empty() || p == "none" {
        if (2..=23).contains(&pattern) {
            // Fallback patterns for unmatched indices
            let p = match pattern % 3 {
                0 => "1,2",
                1 => "6,3",
                _ => "6,3,1,3",
            };
            let scale = weight.max(0.5);
            return p
                .split(',')
                .map(|x| format!("{:.1}", x.parse::<f64>().unwrap_or(1.0) * scale))
                .collect::<Vec<_>>()
                .join(",");
        }
        return String::new();
    }
    if p == "none" {
        return "none".to_string();
    }
    let scale = weight.max(0.5);
    p.split(',')
        .map(|x| format!("{:.1}", x.parse::<f64>().unwrap_or(1.0) * scale))
        .collect::<Vec<_>>()
        .join(",")
}

/// Merge a shape with its master shape data.
pub fn merge_shape_with_master(
    shape: &mut Shape,
    masters: &HashMap<String, HashMap<String, Shape>>,
    parent_master_id: &str,
) {
    let master_id = if !shape.master.is_empty() {
        &shape.master
    } else if !parent_master_id.is_empty() {
        parent_master_id
    } else {
        return;
    };

    let master_shapes = match masters.get(master_id) {
        Some(ms) => ms,
        None => return,
    };

    let master_sd = if !shape.master_shape.is_empty() {
        master_shapes.get(&shape.master_shape)
    } else {
        master_shapes.values().next()
    };

    let master_sd = match master_sd {
        Some(ms) => ms.clone(),
        None => return,
    };

    // Merge cells
    let mut merged_cells = master_sd.cells.clone();
    for (k, v) in &shape.cells {
        if !v.v.is_empty() || !v.f.is_empty() {
            merged_cells.insert(k.clone(), v.clone());
        }
    }
    shape.cells = merged_cells;

    // Merge geometry
    if shape.geometry.is_empty() && !master_sd.geometry.is_empty() {
        shape.geometry = master_sd.geometry.clone();
        if let Some(cv) = master_sd.cells.get("Width") {
            shape.master_w = cv.as_f64();
        }
        if let Some(cv) = master_sd.cells.get("Height") {
            shape.master_h = cv.as_f64();
        }
    } else if !shape.geometry.is_empty() {
        shape.has_own_geometry = true;
    }

    // Merge text
    if shape.text.is_empty()
        && !shape.has_text_elem
        && !master_sd.text.is_empty()
        && shape.shape_type != "Group"
    {
        let txt = &master_sd.text;
        if !matches!(txt.as_str(), "Label" | "Abc" | "Table" | "Entity" | "Class") {
            shape.text = txt.clone();
            if shape.text_parts.is_empty() && !master_sd.text_parts.is_empty() {
                shape.text_parts = master_sd.text_parts.clone();
            }
        }
    }

    // Merge formats
    if shape.char_formats.is_empty() && !master_sd.char_formats.is_empty() {
        shape.char_formats = master_sd.char_formats.clone();
    }
    if shape.para_formats.is_empty() && !master_sd.para_formats.is_empty() {
        shape.para_formats = master_sd.para_formats.clone();
    }
    if shape.foreign_data.is_none() && master_sd.foreign_data.is_some() {
        shape.foreign_data = master_sd.foreign_data.clone();
    }
    if shape.gradient_stops.is_empty() && !master_sd.gradient_stops.is_empty() {
        shape.gradient_stops = master_sd.gradient_stops.clone();
    }
}

/// Compute SVG transform for a shape.
fn compute_transform(shape: &Shape, page_h: f64) -> String {
    let pin_x = shape.cell_f64("PinX") * INCH_TO_PX;
    let pin_y = (page_h - shape.cell_f64("PinY")) * INCH_TO_PX;
    let w = shape.cell_f64("Width");
    let h = shape.cell_f64("Height");

    let lpx_val = shape.cell_val("LocPinX");
    let loc_pin_x = if lpx_val.is_empty() {
        w.abs() * 0.5
    } else {
        lpx_val.parse().unwrap_or(w.abs() * 0.5)
    } * INCH_TO_PX;

    let lpy_val = shape.cell_val("LocPinY");
    let loc_pin_y_raw = if lpy_val.is_empty() {
        h.abs() * 0.5
    } else {
        lpy_val.parse().unwrap_or(h.abs() * 0.5)
    };
    let loc_pin_y = (h.abs() - loc_pin_y_raw) * INCH_TO_PX;

    let angle = shape.cell_f64("Angle");
    let flip_x = shape.cell_val("FlipX") == "1";
    let flip_y = shape.cell_val("FlipY") == "1";

    let mut parts = Vec::new();
    let tx = pin_x - loc_pin_x;
    let ty = pin_y - loc_pin_y;
    parts.push(format!("translate({:.2},{:.2})", tx, ty));

    if angle.abs() > 1e-6 {
        let angle_deg = -angle.to_degrees();
        parts.push(format!(
            "rotate({:.2},{:.2},{:.2})",
            angle_deg, loc_pin_x, loc_pin_y
        ));
    }

    if flip_x || flip_y {
        let sx = if flip_x { -1 } else { 1 };
        let sy = if flip_y { -1 } else { 1 };
        parts.push(format!("translate({:.2},{:.2})", loc_pin_x, loc_pin_y));
        parts.push(format!("scale({},{})", sx, sy));
        parts.push(format!("translate({:.2},{:.2})", -loc_pin_x, -loc_pin_y));
    }

    parts.join(" ")
}

/// Convert geometry to SVG path d attribute.
fn geometry_to_path(geo: &GeomSection, w: f64, h: f64, master_w: f64, master_h: f64) -> String {
    if geo.no_show {
        return String::new();
    }

    let abs_w = if w.abs() > 1e-10 { w.abs() } else { 0.0 };
    let abs_h = if h.abs() > 1e-10 { h.abs() } else { 0.0 };

    let sx = if master_w.abs() > 1e-6 && (master_w.abs() - abs_w).abs() > 1e-6 {
        abs_w / master_w.abs()
    } else {
        1.0
    };
    let sy = if master_h.abs() > 1e-6 && (master_h.abs() - abs_h).abs() > 1e-6 {
        abs_h / master_h.abs()
    } else {
        1.0
    };

    let mut d_parts = Vec::new();
    let mut cx = 0.0_f64;
    let mut cy = 0.0_f64;

    for row in &geo.rows {
        let rt = row.row_type.as_str();
        match rt {
            "MoveTo" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                d_parts.push(format!(
                    "M {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "RelMoveTo" => {
                let x = row.cell_f64("X") * abs_w;
                let y = row.cell_f64("Y") * abs_h;
                d_parts.push(format!(
                    "M {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "LineTo" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                d_parts.push(format!(
                    "L {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "RelLineTo" => {
                let x = row.cell_f64("X") * abs_w;
                let y = row.cell_f64("Y") * abs_h;
                d_parts.push(format!(
                    "L {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "ArcTo" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                let a = row.cell_f64("A") * sy;
                append_arc(&mut d_parts, cx, cy, x, y, a, abs_h);
                cx = x;
                cy = y;
            }
            "EllipticalArcTo" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                let a = row.cell_f64("A") * sx;
                let b = row.cell_f64("B") * sy;
                let c_angle = row.cell_f64("C");
                let d_ratio = row.cell_f64("D");
                append_elliptical_arc(&mut d_parts, cx, cy, x, y, a, b, d_ratio, c_angle, abs_h);
                cx = x;
                cy = y;
            }
            "RelEllipticalArcTo" => {
                let x = row.cell_f64("X") * abs_w;
                let y = row.cell_f64("Y") * abs_h;
                let a = row.cell_f64("A") * abs_w;
                let b = row.cell_f64("B") * abs_h;
                let c_angle = row.cell_f64("C");
                let d_ratio = row.cell_f64("D");
                append_elliptical_arc(&mut d_parts, cx, cy, x, y, a, b, d_ratio, c_angle, abs_h);
                cx = x;
                cy = y;
            }
            "Ellipse" => {
                let ex = row.cell_f64("X") * sx;
                let ey = row.cell_f64("Y") * sy;
                let ea = row.cell_f64("A") * sx;
                let eb = row.cell_f64("B") * sy;
                let ec = row.cell_f64("C") * sx;
                let ed = row.cell_f64("D") * sy;
                let rx = ((ea - ex).powi(2) + (eb - ey).powi(2)).sqrt().max(0.001) * INCH_TO_PX;
                let ry = ((ec - ex).powi(2) + (ed - ey).powi(2)).sqrt().max(0.001) * INCH_TO_PX;
                let cpx = ex * INCH_TO_PX;
                let cpy = (abs_h - ey) * INCH_TO_PX;
                d_parts.push(format!(
                    "M {:.2} {:.2} A {:.2} {:.2} 0 1 0 {:.2} {:.2} A {:.2} {:.2} 0 1 0 {:.2} {:.2} Z",
                    cpx - rx, cpy, rx, ry, cpx + rx, cpy, rx, ry, cpx - rx, cpy
                ));
            }
            "RelCurveTo" | "RelCubBezTo" => {
                let x = row.cell_f64("X") * abs_w;
                let y = row.cell_f64("Y") * abs_h;
                let a = row.cell_f64("A") * abs_w;
                let b = row.cell_f64("B") * abs_h;
                let c = row.cell_f64("C") * abs_w;
                let d = row.cell_f64("D") * abs_h;
                d_parts.push(format!(
                    "C {:.2} {:.2} {:.2} {:.2} {:.2} {:.2}",
                    a * INCH_TO_PX,
                    (abs_h - b) * INCH_TO_PX,
                    c * INCH_TO_PX,
                    (abs_h - d) * INCH_TO_PX,
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "NURBSTo" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                d_parts.push(format!(
                    "L {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "PolylineTo" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                d_parts.push(format!(
                    "L {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                cx = x;
                cy = y;
            }
            "SplineStart" | "SplineKnot" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                if rt == "SplineStart" {
                    d_parts.push(format!(
                        "M {:.2} {:.2}",
                        x * INCH_TO_PX,
                        (abs_h - y) * INCH_TO_PX
                    ));
                } else {
                    d_parts.push(format!(
                        "L {:.2} {:.2}",
                        x * INCH_TO_PX,
                        (abs_h - y) * INCH_TO_PX
                    ));
                }
                cx = x;
                cy = y;
            }
            "InfiniteLine" => {
                let x = row.cell_f64("X") * sx;
                let y = row.cell_f64("Y") * sy;
                let a = row.cell_f64("A") * sx;
                let b = row.cell_f64("B") * sy;
                d_parts.push(format!(
                    "M {:.2} {:.2}",
                    x * INCH_TO_PX,
                    (abs_h - y) * INCH_TO_PX
                ));
                d_parts.push(format!(
                    "L {:.2} {:.2}",
                    a * INCH_TO_PX,
                    (abs_h - b) * INCH_TO_PX
                ));
            }
            _ => {}
        }
    }

    let mut result = d_parts.join(" ");
    if !result.is_empty() && !result.starts_with('M') {
        result = format!("M 0.00 0.00 {}", result);
    }
    result
}

fn append_arc(d_parts: &mut Vec<String>, cx: f64, cy: f64, x: f64, y: f64, bulge: f64, h: f64) {
    if bulge.abs() < 1e-6 {
        d_parts.push(format!(
            "L {:.2} {:.2}",
            x * INCH_TO_PX,
            (h - y) * INCH_TO_PX
        ));
        return;
    }
    let dx = x - cx;
    let dy = y - cy;
    let chord = (dx * dx + dy * dy).sqrt();
    if chord < 1e-10 {
        return;
    }
    let sagitta = bulge.abs();
    let mut radius = (chord * chord / 4.0 + sagitta * sagitta) / (2.0 * sagitta);
    radius = radius.min(chord * 5.0);
    let radius_px = radius * INCH_TO_PX;
    let large_arc = if sagitta > chord / 2.0 { 1 } else { 0 };
    let sweep = if bulge > 0.0 { 0 } else { 1 };
    d_parts.push(format!(
        "A {:.2} {:.2} 0 {} {} {:.2} {:.2}",
        radius_px,
        radius_px,
        large_arc,
        sweep,
        x * INCH_TO_PX,
        (h - y) * INCH_TO_PX
    ));
}

fn append_elliptical_arc(
    d_parts: &mut Vec<String>,
    cx: f64,
    cy: f64,
    x: f64,
    y: f64,
    a: f64,
    b: f64,
    mut d_ratio: f64,
    c_angle: f64,
    h: f64,
) {
    let chord = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt();
    if chord < 1e-10 {
        return;
    }
    let mid_x = (cx + x) / 2.0;
    let mid_y = (cy + y) / 2.0;
    let dist_ctrl = ((a - mid_x).powi(2) + (b - mid_y).powi(2)).sqrt();
    if dist_ctrl < 1e-6 && (d_ratio - 1.0).abs() < 0.01 {
        d_parts.push(format!(
            "L {:.2} {:.2}",
            x * INCH_TO_PX,
            (h - y) * INCH_TO_PX
        ));
        return;
    }
    let angle_deg = if c_angle != 0.0 {
        c_angle.to_degrees()
    } else {
        0.0
    };
    if d_ratio < 0.001 {
        d_ratio = 1.0;
    }
    let half_chord = chord / 2.0;
    let cos_a = if c_angle != 0.0 {
        (-c_angle).cos()
    } else {
        1.0
    };
    let sin_a = if c_angle != 0.0 {
        (-c_angle).sin()
    } else {
        0.0
    };
    let p3_dx = a - mid_x;
    let p3_dy = b - mid_y;
    let p3_lx = cos_a * p3_dx + sin_a * p3_dy;
    let p3_ly = -sin_a * p3_dx + cos_a * p3_dy;
    let sagitta = (p3_lx * p3_lx + p3_ly * p3_ly).sqrt();
    if sagitta < 1e-6 {
        d_parts.push(format!(
            "L {:.2} {:.2}",
            x * INCH_TO_PX,
            (h - y) * INCH_TO_PX
        ));
        return;
    }
    let r = ((half_chord.powi(2) + sagitta.powi(2)) / (2.0 * sagitta)).min(chord * 5.0);
    let rx = r.abs() * INCH_TO_PX;
    let ry = if d_ratio != 0.0 {
        (r / d_ratio).abs() * INCH_TO_PX
    } else {
        rx
    };
    let cross = (x - cx) * (b - cy) - (y - cy) * (a - cx);
    let sweep = if cross < 0.0 { 0 } else { 1 };
    let large_arc = if sagitta > half_chord { 1 } else { 0 };
    d_parts.push(format!(
        "A {:.2} {:.2} {:.1} {} {} {:.2} {:.2}",
        rx.max(0.1),
        ry.max(0.1),
        angle_deg,
        large_arc,
        sweep,
        x * INCH_TO_PX,
        (h - y) * INCH_TO_PX
    ));
}

/// Build connector polyline from geometry rows, transforming to page coordinates.
fn build_connector_polyline(
    shape: &Shape,
    page_h: f64,
    bx: f64,
    by: f64,
) -> Vec<(f64, f64)> {
    let pin_x = shape.cell_f64("PinX");
    let pin_y = shape.cell_f64("PinY");
    let loc_pin_x = shape.cell_f64("LocPinX");
    let loc_pin_y = shape.cell_f64("LocPinY");
    let angle = shape.cell_f64("Angle");
    let cos_a = if angle.abs() > 1e-6 { angle.cos() } else { 1.0 };
    let sin_a = if angle.abs() > 1e-6 { angle.sin() } else { 0.0 };

    let mut points = Vec::new();
    let mut has_move_to = false;

    for geo in &shape.geometry {
        if geo.no_show {
            continue;
        }
        for row in &geo.rows {
            let rt = row.row_type.as_str();
            match rt {
                "MoveTo" | "LineTo" | "ArcTo" | "EllipticalArcTo" | "NURBSTo"
                | "SplineStart" | "SplineKnot" => {
                    let x_cell = row.cells.get("X");
                    let y_cell = row.cells.get("Y");
                    // Both X and Y must be present
                    let x_val = x_cell.map(|c| &c.v).filter(|v| !v.is_empty());
                    let y_val = y_cell.map(|c| &c.v).filter(|v| !v.is_empty());
                    if x_val.is_none() && x_cell.map(|c| c.v.as_str()) != Some("0") {
                        continue;
                    }
                    if y_val.is_none() && y_cell.map(|c| c.v.as_str()) != Some("0") {
                        continue;
                    }
                    if rt == "MoveTo" {
                        has_move_to = true;
                    }
                    let lx = row.cell_f64("X");
                    let ly = row.cell_f64("Y");
                    // Local to page coordinates
                    let dx = lx - loc_pin_x;
                    let dy = ly - loc_pin_y;
                    let px = pin_x + dx * cos_a - dy * sin_a;
                    let py = pin_y + dx * sin_a + dy * cos_a;
                    let sx_px = px * INCH_TO_PX;
                    let sy_px = (page_h - py) * INCH_TO_PX;
                    points.push((sx_px, sy_px));
                }
                _ => {}
            }
        }
    }

    // If no MoveTo, prepend the begin point
    if !points.is_empty() && !has_move_to {
        points.insert(0, (bx, by));
    }

    points
}

/// Render all shapes on a page to SVG.
pub fn shapes_to_svg(
    shapes: &[Shape],
    page_w: f64,
    page_h: f64,
    masters: &HashMap<String, HashMap<String, Shape>>,
    _connects: &[Connect],
    media: &HashMap<String, Vec<u8>>,
    page_rels: &HashMap<String, String>,
    bg_shapes: Option<&[Shape]>,
    theme_colors: &HashMap<String, String>,
    layers: &HashMap<String, LayerDef>,
) -> String {
    let page_w_px = page_w * INCH_TO_PX;
    let page_h_px = page_h * INCH_TO_PX;

    // Compute content bounding box
    let mut vb_x = 0.0_f64;
    let mut vb_y = 0.0_f64;
    let mut vb_w = page_w_px;
    let mut vb_h = page_h_px;

    let all_shapes: Vec<&Shape> = shapes
        .iter()
        .chain(bg_shapes.unwrap_or(&[]).iter())
        .collect();

    if !all_shapes.is_empty() {
        let mut min_x = f64::MAX;
        let mut min_y = f64::MAX;
        let mut max_x = f64::MIN;
        let mut max_y = f64::MIN;

        for s in &all_shapes {
            let px = s.cell_f64("PinX") * INCH_TO_PX;
            let py = (page_h - s.cell_f64("PinY")) * INCH_TO_PX;
            let sw = s.cell_f64("Width").abs() * INCH_TO_PX;
            let sh = s.cell_f64("Height").abs() * INCH_TO_PX;
            if px > 0.0 || py > 0.0 {
                min_x = min_x.min(px - sw / 2.0);
                min_y = min_y.min(py - sh / 2.0);
                max_x = max_x.max(px + sw / 2.0);
                max_y = max_y.max(py + sh / 2.0);
            }
        }

        if min_x < f64::MAX {
            let content_w = max_x - min_x;
            let content_h = max_y - min_y;
            let pad_x = (content_w * 0.08).max(50.0);
            let pad_y = (content_h * 0.08).max(50.0);
            vb_x = min_x.min(0.0) - pad_x;
            vb_y = min_y.min(0.0) - pad_y;
            vb_w = (content_w + 2.0 * pad_x).max(page_w_px * 0.5);
            vb_h = (content_h + 2.0 * pad_y).max(page_h_px * 0.5);
            vb_w = vb_w.max(max_x + pad_x - vb_x);
            vb_h = vb_h.max(max_y + pad_y - vb_y);
        }
    }

    let max_svg_px = 4000.0;
    let mut display_w = vb_w;
    let mut display_h = vb_h;
    if vb_w.max(vb_h) > max_svg_px {
        let scale = max_svg_px / vb_w.max(vb_h);
        display_w = vb_w * scale;
        display_h = vb_h * scale;
    }

    let mut svg = Vec::new();
    svg.push(r#"<?xml version="1.0" encoding="UTF-8"?>"#.to_string());
    svg.push(format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{:.0}" height="{:.0}" viewBox="{:.0} {:.0} {:.0} {:.0}">"#,
        display_w, display_h, vb_x, vb_y, vb_w, vb_h
    ));
    svg.push(format!(
        r#"<rect x="{:.0}" y="{:.0}" width="{:.0}" height="{:.0}" fill="white"/>"#,
        vb_x, vb_y, vb_w, vb_h
    ));

    let mut used_markers: HashSet<String> = HashSet::new();
    let mut gradients: Vec<GradientDef> = Vec::new();
    let mut fill_patterns: Vec<FillPatternDef> = Vec::new();
    let mut shadow_defs: Vec<String> = Vec::new();
    let mut text_layer: Vec<String> = Vec::new();

    // Render background shapes
    if let Some(bg) = bg_shapes {
        svg.push("<!-- Background page -->".to_string());
        for s in bg {
            let mut shape = s.clone();
            merge_shape_with_master(&mut shape, masters, "");
            let elements = render_shape_svg(
                &shape,
                page_h,
                masters,
                "",
                0,
                media,
                page_rels,
                &mut used_markers,
                theme_colors,
                layers,
                &mut gradients,
                &mut fill_patterns,
                &mut shadow_defs,
                &mut text_layer,
            );
            svg.extend(elements);
        }
    }

    // Sort: containers first (they should be behind other shapes)
    let mut sorted_shapes: Vec<&Shape> = shapes.iter().collect();
    sorted_shapes.sort_by_key(|s| {
        let user = &s.user;
        let st = user
            .get("msvStructureType")
            .and_then(|m| m.get("Value"))
            .map(|v| v.as_str())
            .unwrap_or("");
        let name = s.name_u.to_lowercase();
        if st == "Container" || name.contains("container") || name.contains("swimlane") {
            0
        } else {
            1
        }
    });

    // Render shapes
    for s in sorted_shapes {
        let mut shape = s.clone();
        merge_shape_with_master(&mut shape, masters, "");
        let elements = render_shape_svg(
            &shape,
            page_h,
            masters,
            "",
            0,
            media,
            page_rels,
            &mut used_markers,
            theme_colors,
            layers,
            &mut gradients,
            &mut fill_patterns,
            &mut shadow_defs,
            &mut text_layer,
        );
        svg.extend(elements);
    }

    // Text layer on top
    if !text_layer.is_empty() {
        svg.push("<!-- Text layer -->".to_string());
        svg.extend(text_layer);
    }

    svg.push("</svg>".to_string());

    // Insert defs block after background rect
    let mut defs = Vec::new();
    if !used_markers.is_empty()
        || !gradients.is_empty()
        || !fill_patterns.is_empty()
        || !shadow_defs.is_empty()
    {
        defs.push("<defs>".to_string());

        // Arrow markers
        let mut sorted_markers: Vec<&String> = used_markers.iter().collect();
        sorted_markers.sort();
        for marker_id in sorted_markers {
            let parts: Vec<&str> = marker_id.split('_').collect();
            let direction = parts.get(1).unwrap_or(&"end");
            let size_idx: i32 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(3);
            let color = parts
                .get(3)
                .map(|c| format!("#{}", c))
                .unwrap_or_else(|| "#333333".to_string());
            let scale = arrow_size(size_idx);
            let mw = 10.0 * scale;
            let mh = 7.0 * scale;
            if *direction == "start" {
                defs.push(format!(
                    r#"<marker id="{}" markerWidth="{:.1}" markerHeight="{:.1}" refX="0" refY="{:.1}" orient="auto" markerUnits="userSpaceOnUse"><polygon points="{:.1} 0, 0 {:.1}, {:.1} {:.1}" fill="{}"/></marker>"#,
                    marker_id, mw, mh, mh / 2.0, mw, mh / 2.0, mw, mh, color
                ));
            } else {
                defs.push(format!(
                    r#"<marker id="{}" markerWidth="{:.1}" markerHeight="{:.1}" refX="{:.1}" refY="{:.1}" orient="auto" markerUnits="userSpaceOnUse"><polygon points="0 0, {:.1} {:.1}, 0 {:.1}" fill="{}"/></marker>"#,
                    marker_id, mw, mh, mw, mh / 2.0, mw, mh / 2.0, mh, color
                ));
            }
        }

        // Fill patterns (hatching) — complete implementation for all Visio patterns 2-24
        for pat in &fill_patterns {
            let pt = pat.pattern_type;
            let sw = 1.0;

            if (2..=5).contains(&pt) {
                // Simple line patterns: horizontal, vertical, diagonal
                let spacing = 6;
                let line = match pt {
                    2 => format!(
                        r#"<line x1="0" y1="{}" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/>"#,
                        spacing / 2, spacing, spacing / 2, pat.fg, sw
                    ),
                    3 => format!(
                        r#"<line x1="{}" y1="0" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/>"#,
                        spacing / 2, spacing / 2, spacing, pat.fg, sw
                    ),
                    4 => format!(
                        r#"<line x1="0" y1="{}" x2="{}" y2="0" stroke="{}" stroke-width="{}"/>"#,
                        spacing, spacing, pat.fg, sw
                    ),
                    _ => format!(
                        r#"<line x1="0" y1="0" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/>"#,
                        spacing, spacing, pat.fg, sw
                    ),
                };
                defs.push(format!(
                    r#"<pattern id="{}" patternUnits="userSpaceOnUse" width="{}" height="{}"><rect width="{}" height="{}" fill="{}"/>{}</pattern>"#,
                    pat.id, spacing, spacing, spacing, spacing, pat.bg, line
                ));
            } else if (6..=9).contains(&pt) {
                // Crosshatch patterns
                let spacing = 6;
                defs.push(format!(
                    r#"<pattern id="{}" patternUnits="userSpaceOnUse" width="{}" height="{}"><rect width="{}" height="{}" fill="{}"/><line x1="0" y1="{}" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/><line x1="{}" y1="0" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/></pattern>"#,
                    pat.id, spacing, spacing, spacing, spacing, pat.bg,
                    spacing / 2, spacing, spacing / 2, pat.fg, sw,
                    spacing / 2, spacing / 2, spacing, pat.fg, sw
                ));
            } else if (10..=12).contains(&pt) {
                // Diagonal crosshatch
                let spacing = 6;
                defs.push(format!(
                    r#"<pattern id="{}" patternUnits="userSpaceOnUse" width="{}" height="{}"><rect width="{}" height="{}" fill="{}"/><line x1="0" y1="0" x2="{}" y2="{}" stroke="{}" stroke-width="{}"/><line x1="0" y1="{}" x2="{}" y2="0" stroke="{}" stroke-width="{}"/></pattern>"#,
                    pat.id, spacing, spacing, spacing, spacing, pat.bg,
                    spacing, spacing, pat.fg, sw,
                    spacing, spacing, pat.fg, sw
                ));
            } else if (13..=24).contains(&pt) {
                // Dense patterns — dots with varying spacing
                let dot_spacing = (3i32).max(6 - (pt - 12));
                defs.push(format!(
                    r#"<pattern id="{}" patternUnits="userSpaceOnUse" width="{}" height="{}"><rect width="{}" height="{}" fill="{}"/><circle cx="{}" cy="{}" r="0.8" fill="{}"/></pattern>"#,
                    pat.id, dot_spacing, dot_spacing, dot_spacing, dot_spacing, pat.bg,
                    dot_spacing as f64 / 2.0, dot_spacing as f64 / 2.0, pat.fg
                ));
            } else {
                // Unknown pattern — fallback to dots
                let spacing = 6;
                defs.push(format!(
                    r#"<pattern id="{}" patternUnits="userSpaceOnUse" width="{}" height="{}"><rect width="{}" height="{}" fill="{}"/><circle cx="3" cy="3" r="0.8" fill="{}"/></pattern>"#,
                    pat.id, spacing, spacing, spacing, spacing, pat.bg, pat.fg
                ));
            }
        }

        // Gradients
        for grad in &gradients {
            let stops = if !grad.stops.is_empty() {
                grad.stops
                    .iter()
                    .map(|s| {
                        format!(
                            r#"<stop offset="{}%" stop-color="{}"/>"#,
                            s.position, s.color
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("")
            } else {
                let mut s = vec![format!(
                    r#"<stop offset="0%" stop-color="{}"/>"#,
                    grad.start
                )];
                if let Some(mid) = &grad.mid {
                    s.push(format!(r#"<stop offset="50%" stop-color="{}"/>"#, mid));
                }
                s.push(format!(
                    r#"<stop offset="100%" stop-color="{}"/>"#,
                    grad.end
                ));
                s.join("")
            };

            if grad.radial {
                defs.push(format!(
                    r#"<radialGradient id="{}" cx="{}%" cy="{}%" r="{}%" fx="{}%" fy="{}%">{}</radialGradient>"#,
                    grad.id, grad.cx, grad.cy, grad.r, grad.fx, grad.fy, stops
                ));
            } else {
                let rad = grad.dir.to_radians();
                let x1 = 50.0 - 50.0 * rad.cos();
                let y1 = 50.0 + 50.0 * rad.sin();
                let x2 = 50.0 + 50.0 * rad.cos();
                let y2 = 50.0 - 50.0 * rad.sin();
                defs.push(format!(
                    r#"<linearGradient id="{}" x1="{:.1}%" y1="{:.1}%" x2="{:.1}%" y2="{:.1}%">{}</linearGradient>"#,
                    grad.id, x1, y1, x2, y2, stops
                ));
            }
        }

        // Shadow filters
        for sdef in &shadow_defs {
            defs.push(sdef.clone());
        }

        defs.push("</defs>".to_string());
    }

    // Insert defs after line 3 (after background rect)
    if !defs.is_empty() {
        for (j, line) in defs.into_iter().enumerate() {
            svg.insert(3 + j, line);
        }
    }

    svg.join("\n")
}

/// Render a single shape as SVG elements.
#[allow(clippy::too_many_arguments)]
fn render_shape_svg(
    shape: &Shape,
    page_h: f64,
    masters: &HashMap<String, HashMap<String, Shape>>,
    parent_master_id: &str,
    depth: usize,
    media: &HashMap<String, Vec<u8>>,
    page_rels: &HashMap<String, String>,
    used_markers: &mut HashSet<String>,
    theme_colors: &HashMap<String, String>,
    layers: &HashMap<String, LayerDef>,
    gradients: &mut Vec<GradientDef>,
    fill_patterns: &mut Vec<FillPatternDef>,
    shadow_defs: &mut Vec<String>,
    text_layer: &mut Vec<String>,
) -> Vec<String> {
    let mut lines = Vec::new();

    // Skip invisible shapes
    if shape.cell_val("Visible") == "0" {
        return lines;
    }

    // Layer visibility check
    let layer_member = shape.cell_val("LayerMember");
    if !layer_member.is_empty() && !layers.is_empty() {
        let layer_ids: Vec<&str> = layer_member.split(';').collect();
        let all_hidden = layer_ids
            .iter()
            .all(|lid| layers.get(lid.trim()).map(|l| !l.visible).unwrap_or(false));
        if all_hidden {
            return lines;
        }
    }

    let w_inch = shape.cell_f64("Width");
    let h_inch = shape.cell_f64("Height");
    let w_px = w_inch.abs() * INCH_TO_PX;
    let h_px = h_inch.abs() * INCH_TO_PX;

    // Line style
    let mut line_weight = shape.cell_f64_or("LineWeight", 0.01) * INCH_TO_PX;
    if line_weight < 0.5 {
        line_weight = 1.5;
    } else if line_weight > 20.0 {
        line_weight = 20.0;
    }

    let line_color = {
        let c = resolve_color(shape.cell_val("LineColor"), theme_colors);
        if c.is_empty() {
            "#333333".to_string()
        } else {
            c
        }
    };

    let fill_foregnd = resolve_color(shape.cell_val("FillForegnd"), theme_colors);
    let fill_bkgnd = resolve_color(shape.cell_val("FillBkgnd"), theme_colors);

    let fill_pat_int: i32 = shape.cell_val("FillPattern").parse().unwrap_or(1);
    let line_pattern: i32 = shape.cell_val("LinePattern").parse().unwrap_or(1);

    // Determine fill color — handles solid fills, hatching patterns (2-24),
    // and gradient fills (25-40)
    let fill = if fill_pat_int == 0 {
        "none".to_string()
    } else if fill_pat_int == 1 {
        // Solid fill
        if !fill_foregnd.is_empty() {
            fill_foregnd.clone()
        } else if !fill_bkgnd.is_empty() {
            fill_bkgnd.clone()
        } else {
            "none".to_string()
        }
    } else if (25..=40).contains(&fill_pat_int) {
        // Gradient fills
        let fg = if !fill_foregnd.is_empty() {
            fill_foregnd.clone()
        } else {
            "#FFFFFF".to_string()
        };
        let bg = if !fill_bkgnd.is_empty() {
            fill_bkgnd.clone()
        } else {
            "#000000".to_string()
        };
        let grad_angle = pattern_angle(fill_pat_int);
        let grad_id = format!("grad_{}_{}", shape.id, fill_pat_int);
        let is_radial = matches!(fill_pat_int, 29 | 30 | 31 | 32 | 37 | 38 | 39);

        // Use gradient stops from shape if available
        let stops = if !shape.gradient_stops.is_empty() {
            shape.gradient_stops.iter().flatten().map(|gs| {
                GradientStop {
                    position: gs.position,
                    color: gs.color.clone(),
                }
            }).collect()
        } else {
            vec![
                GradientStop { position: 0.0, color: fg.clone() },
                GradientStop { position: 100.0, color: bg.clone() },
            ]
        };

        gradients.push(GradientDef {
            id: grad_id.clone(),
            start: fg,
            end: bg,
            mid: None,
            dir: grad_angle,
            radial: is_radial,
            stops,
            cx: 50.0,
            cy: 50.0,
            fx: 50.0,
            fy: 50.0,
            r: 50.0,
        });
        format!("url(#{})", grad_id)
    } else if (2..=24).contains(&fill_pat_int) {
        // Hatching patterns
        let fg = if !fill_foregnd.is_empty() {
            fill_foregnd.clone()
        } else {
            "#000000".to_string()
        };
        let bg = if !fill_bkgnd.is_empty() {
            fill_bkgnd.clone()
        } else {
            "#FFFFFF".to_string()
        };
        let pat_id = format!("fpat_{}_{}", shape.id, fill_pat_int);
        fill_patterns.push(FillPatternDef {
            id: pat_id.clone(),
            fg,
            bg,
            pattern_type: fill_pat_int,
        });
        format!("url(#{})", pat_id)
    } else if !fill_foregnd.is_empty() {
        fill_foregnd.clone()
    } else if !fill_bkgnd.is_empty() {
        fill_bkgnd.clone()
    } else {
        "none".to_string()
    };

    let stroke = if line_pattern != 0 {
        &line_color
    } else {
        "none"
    };
    let dash_array = get_dash_array(line_pattern, line_weight);

    // Fill opacity
    let fill_trans = shape.cell_f64("FillForegndTrans");
    let fill_opacity = if fill_trans > 0.0 && fill_trans <= 1.0 {
        1.0 - fill_trans
    } else if fill_trans > 1.0 {
        1.0 - fill_trans / 100.0
    } else {
        1.0
    };

    // Shadow
    let shadow_val = shape.cell_val("ShdwPattern");
    let has_shadow = !shadow_val.is_empty() && shadow_val != "0";
    let shadow_attr = if has_shadow {
        let shadow_id = format!("shadow_{}", shape.id);
        let shadow_offset_x = shape.cell_f64_or("ShdwOffsetX", 0.02) * INCH_TO_PX;
        let shadow_offset_y = shape.cell_f64_or("ShdwOffsetY", -0.02) * INCH_TO_PX;
        shadow_defs.push(format!(
            "<filter id=\"{}\"><feDropShadow dx=\"{:.1}\" dy=\"{:.1}\" stdDeviation=\"2\" flood-color=\"#00000044\"/></filter>",
            shadow_id, shadow_offset_x, -shadow_offset_y
        ));
        format!(r#" filter="url(#{})""#, shadow_id)
    } else {
        String::new()
    };

    // Check for 1D connector
    let begin_x = shape.cell_val("BeginX");
    let end_x = shape.cell_val("EndX");
    let is_1d = !begin_x.is_empty() && !end_x.is_empty();
    let obj_type = shape.cell_val("ObjType").to_string();
    let is_1d_group = (shape.shape_type == "Group" || !shape.sub_shapes.is_empty()) && is_1d;
    let shape_name = shape.name_u.to_lowercase();
    let has_geometry = !shape.geometry.is_empty()
        && shape.geometry.iter().any(|g| !g.no_show && !g.rows.is_empty());

    // Group rendering
    if (shape.shape_type == "Group" || !shape.sub_shapes.is_empty()) && !is_1d_group {
        let transform = compute_transform(shape, page_h);
        let group_master_id = if !shape.master.is_empty() {
            &shape.master
        } else {
            parent_master_id
        };
        let group_h = h_inch;

        lines.push(format!(r#"<g transform="{}"{}>"#, transform, shadow_attr));

        // Render group's own geometry
        for geo in &shape.geometry {
            let path_d = geometry_to_path(geo, w_inch, h_inch, shape.master_w, shape.master_h);
            if path_d.is_empty() {
                continue;
            }
            let geo_fill = if geo.no_fill { "none" } else { &fill };
            let geo_stroke = if geo.no_line { "none" } else { stroke };
            let mut style = format!(
                r#"fill="{}" stroke="{}" stroke-width="{:.2}""#,
                geo_fill, geo_stroke, line_weight
            );
            if fill_opacity < 0.99 && geo_fill != "none" {
                style.push_str(&format!(r#" fill-opacity="{:.2}""#, fill_opacity));
            }
            if !dash_array.is_empty() && dash_array != "none" {
                style.push_str(&format!(r#" stroke-dasharray="{}""#, dash_array));
            }
            lines.push(format!(r#"<path d="{}" {}/>"#, path_d, style));
        }

        // Render sub-shapes
        for sub in &shape.sub_shapes {
            let mut sub_shape = sub.clone();
            merge_shape_with_master(&mut sub_shape, masters, group_master_id);
            let sub_elements = render_shape_svg(
                &sub_shape,
                group_h,
                masters,
                group_master_id,
                depth + 1,
                media,
                page_rels,
                used_markers,
                theme_colors,
                layers,
                gradients,
                fill_patterns,
                shadow_defs,
                text_layer,
            );
            lines.extend(sub_elements);
        }

        lines.push("</g>".to_string());

        // Group text
        if !shape.text.is_empty() && depth == 0 {
            append_text_svg(text_layer, shape, page_h, w_px, h_px, theme_colors, is_1d);
        } else if !shape.text.is_empty() {
            append_text_svg(&mut lines, shape, page_h, w_px, h_px, theme_colors, is_1d);
        }

        return lines;
    }

    let transform = compute_transform(shape, page_h);

    // 1D connector rendering — comprehensive with geometry-based routing
    let is_connector = is_1d || obj_type == "2";
    if is_connector && is_1d {
        let mut stroke_width = line_weight;
        if stroke_width < 1.0 {
            stroke_width = 1.5;
        }

        let bx = begin_x.parse::<f64>().unwrap_or(0.0) * INCH_TO_PX;
        let by = (page_h - shape.cell_val("BeginY").parse::<f64>().unwrap_or(0.0)) * INCH_TO_PX;
        let ex_px = end_x.parse::<f64>().unwrap_or(0.0) * INCH_TO_PX;
        let ey_px = (page_h - shape.cell_val("EndY").parse::<f64>().unwrap_or(0.0)) * INCH_TO_PX;

        // Arrow markers
        let mut end_arrow: i32 = shape.cell_val("EndArrow").parse().unwrap_or(0);
        let begin_arrow: i32 = shape.cell_val("BeginArrow").parse().unwrap_or(0);
        let end_arrow_size: i32 = shape.cell_val("EndArrowSize").parse().unwrap_or(2);
        let begin_arrow_size: i32 = shape.cell_val("BeginArrowSize").parse().unwrap_or(2);

        // Default to arrow for connector-type shapes
        let is_named_connector = shape_name.contains("connector");
        if end_arrow == 0 && (obj_type == "2" || is_named_connector) {
            let ea_cell = shape.cells.get("EndArrow");
            if ea_cell.is_none() || ea_cell.map(|c| c.v.is_empty() && c.f.is_empty()).unwrap_or(true) {
                end_arrow = 4;
            }
        }

        let marker_color = stroke.trim_start_matches('#');
        let mut marker_attrs = String::new();
        if begin_arrow > 0 {
            let mid = format!("arrow_start_{}_{}", begin_arrow_size, marker_color);
            used_markers.insert(mid.clone());
            marker_attrs.push_str(&format!(r#" marker-start="url(#{})""#, mid));
        }
        if end_arrow > 0 {
            let mid = format!("arrow_end_{}_{}", end_arrow_size, marker_color);
            used_markers.insert(mid.clone());
            marker_attrs.push_str(&format!(r#" marker-end="url(#{})""#, mid));
        }

        let dash_attr = if !dash_array.is_empty() && dash_array != "none" {
            format!(r#" stroke-dasharray="{}""#, dash_array)
        } else {
            String::new()
        };

        // Try geometry-based routing first (for connectors with PinX)
        let has_pin_x = shape.cells.contains_key("PinX");
        if has_geometry && has_pin_x {
            let points = build_connector_polyline(shape, page_h, bx, by);
            if points.len() >= 2 {
                let mut d_parts = vec![format!("M {:.2} {:.2}", points[0].0, points[0].1)];
                for pt in &points[1..] {
                    d_parts.push(format!("L {:.2} {:.2}", pt.0, pt.1));
                }
                let path_d = d_parts.join(" ");
                lines.push(format!(
                    r#"<path d="{}" fill="none" stroke="{}" stroke-width="{:.2}"{}{} stroke-linejoin="round"/>"#,
                    path_d, stroke, stroke_width, dash_attr, marker_attrs
                ));
            } else {
                // Fallback to straight line
                lines.push(format!(
                    r#"<line x1="{:.2}" y1="{:.2}" x2="{:.2}" y2="{:.2}" stroke="{}" stroke-width="{:.2}"{}{}/>
"#,
                    bx, by, ex_px, ey_px, stroke, stroke_width, dash_attr, marker_attrs
                ));
            }
        } else {
            // No geometry — use orthogonal routing when both axes differ
            let dx = (ex_px - bx).abs();
            let dy = (ey_px - by).abs();
            if dx > 5.0 && dy > 5.0 {
                // L/Z-shaped orthogonal route
                let mid_y = (by + ey_px) / 2.0;
                let path_d = format!(
                    "M {:.2} {:.2} L {:.2} {:.2} L {:.2} {:.2} L {:.2} {:.2}",
                    bx, by, bx, mid_y, ex_px, mid_y, ex_px, ey_px
                );
                lines.push(format!(
                    r#"<path d="{}" fill="none" stroke="{}" stroke-width="{:.2}"{}{} stroke-linejoin="round"/>"#,
                    path_d, stroke, stroke_width, dash_attr, marker_attrs
                ));
            } else {
                // Straight line for horizontal/vertical connectors
                lines.push(format!(
                    r#"<line x1="{:.2}" y1="{:.2}" x2="{:.2}" y2="{:.2}" stroke="{}" stroke-width="{:.2}"{}{}/>
"#,
                    bx, by, ex_px, ey_px, stroke, stroke_width, dash_attr, marker_attrs
                ));
            }
        }
    } else if !shape.geometry.is_empty() {
        // 2D shape with geometry
        for geo in &shape.geometry {
            let path_d = geometry_to_path(geo, w_inch, h_inch, shape.master_w, shape.master_h);
            if path_d.is_empty() {
                continue;
            }
            let geo_fill = if geo.no_fill { "none" } else { &fill };
            let geo_stroke = if geo.no_line { "none" } else { stroke };

            let mut style = format!(
                r#"fill="{}" stroke="{}" stroke-width="{:.2}""#,
                geo_fill, geo_stroke, line_weight
            );
            if fill_opacity < 0.99 && geo_fill != "none" {
                style.push_str(&format!(r#" fill-opacity="{:.2}""#, fill_opacity));
            }
            if !dash_array.is_empty() && dash_array != "none" {
                style.push_str(&format!(r#" stroke-dasharray="{}""#, dash_array));
            }
            if !shadow_attr.is_empty() {
                style.push_str(&shadow_attr);
            }
            lines.push(format!(
                r#"<path d="{}" {} transform="{}"/>"#,
                path_d, style, transform
            ));
        }
    } else if w_px > 0.0 && h_px > 0.0 && (fill != "none" || !shape.text.is_empty()) {
        // Fallback rectangle
        let fallback_fill = if fill != "none" { &fill } else { "#FAFAFA" };
        let fallback_stroke = if stroke != "none" { stroke } else { "#CCCCCC" };
        lines.push(format!(
            r#"<rect x="0" y="0" width="{:.2}" height="{:.2}" fill="{}" stroke="{}" stroke-width="{:.2}" rx="4"{} transform="{}"/>"#,
            w_px, h_px, fallback_fill, fallback_stroke, line_weight.max(0.75), shadow_attr, transform
        ));
    }

    // Embedded image rendering
    if let Some(ref fd) = shape.foreign_data {
        if let Some(ref data) = fd.data {
            if !data.is_empty() {
                let mime = match fd.foreign_type.as_str() {
                    "PNG" | "png" => "image/png",
                    "JPEG" | "jpeg" | "JPG" | "jpg" => "image/jpeg",
                    "GIF" | "gif" => "image/gif",
                    "BMP" | "bmp" => "image/bmp",
                    "SVG" | "svg" => "image/svg+xml",
                    _ => "image/png",
                };
                let img_url = format!("data:{};base64,{}", mime, data);
                lines.push(format!(
                    r#"<image x="0" y="0" width="{:.2}" height="{:.2}" href="{}" transform="{}"/>"#,
                    w_px, h_px, img_url, transform
                ));
            }
        }
    }

    // Text rendering
    if !shape.text.is_empty() {
        if depth == 0 {
            append_text_svg(text_layer, shape, page_h, w_px, h_px, theme_colors, is_1d);
        } else {
            append_text_svg(&mut lines, shape, page_h, w_px, h_px, theme_colors, is_1d);
        }
    }

    lines
}

/// Append SVG text elements for a shape.
fn append_text_svg(
    lines: &mut Vec<String>,
    shape: &Shape,
    page_h: f64,
    _w_px: f64,
    _h_px: f64,
    theme_colors: &HashMap<String, String>,
    is_1d: bool,
) {
    let text = &shape.text;
    if text.is_empty() {
        return;
    }

    let pin_x = shape.cell_f64("PinX") * INCH_TO_PX;
    let pin_y = (page_h - shape.cell_f64("PinY")) * INCH_TO_PX;

    let char_fmt = shape.char_formats.get("0").cloned().unwrap_or_default();
    let mut font_size = char_fmt.size.parse::<f64>().unwrap_or(0.1111) * INCH_TO_PX;
    if font_size < 6.0 {
        font_size = 8.0;
    } else if font_size > 72.0 {
        font_size = 72.0;
    }

    let text_color = {
        // Check theme text color override first
        let theme_tc = shape.theme_text_color.as_deref().unwrap_or("");
        let c = if !theme_tc.is_empty() {
            theme_tc.to_string()
        } else {
            resolve_color(&char_fmt.color, theme_colors)
        };
        if c.is_empty() {
            "#000000".to_string()
        } else {
            c
        }
    };

    let font_family = if char_fmt.font.is_empty() || char_fmt.font == "Themed" {
        "Noto Sans, sans-serif".to_string()
    } else {
        format!("{}, Noto Sans, sans-serif", char_fmt.font)
    };

    let para_fmt = shape.para_formats.get("0").cloned().unwrap_or_default();
    let halign: i32 = para_fmt.horiz_align.parse().unwrap_or(1);
    let text_anchor = match halign {
        0 => "start",
        2 => "end",
        _ => "middle",
    };

    let style_bits: i32 = char_fmt.style.parse().unwrap_or(0);
    let fw = if style_bits & 1 != 0 {
        r#" font-weight="bold""#
    } else {
        ""
    };
    let fs = if style_bits & 2 != 0 {
        r#" font-style="italic""#
    } else {
        ""
    };
    // Underline
    let td = if style_bits & 4 != 0 {
        r#" text-decoration="underline""#
    } else {
        ""
    };

    let tx = pin_x;
    let ty = pin_y;

    let text_lines: Vec<&str> = text.split('\n').collect();
    let total_height = text_lines.len() as f64 * font_size * 1.2;

    // For 1D connectors, offset text above the line
    let y_offset = if is_1d { -font_size * 0.8 } else { 0.0 };

    let start_y = ty - total_height / 2.0 + font_size * 0.6 + y_offset;

    // For connector labels, add a white background for readability
    if is_1d && !text.trim().is_empty() {
        let text_w = text.len() as f64 * font_size * 0.55;
        let bg_x = tx - text_w / 2.0 - 2.0;
        let bg_y = start_y - font_size * 0.85;
        let bg_w = text_w + 4.0;
        let bg_h = total_height + 4.0;
        lines.push(format!(
            r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" fill="white" fill-opacity="0.85" rx="2"/>"#,
            bg_x, bg_y, bg_w, bg_h
        ));
    }

    for (j, tline) in text_lines.iter().enumerate() {
        let trimmed = tline.trim();
        if trimmed.is_empty() {
            continue;
        }
        let escaped = escape_xml(trimmed);
        let ly = start_y + j as f64 * font_size * 1.2;
        lines.push(format!(
            r#"<text x="{:.2}" y="{:.2}" text-anchor="{}" font-family="{}" font-size="{:.1}" fill="{}"{}{}{}>
{}</text>"#,
            tx, ly, text_anchor, font_family, font_size, text_color, fw, fs, td, escaped
        ));
    }
}