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
|
#if !PLATFORM_WINDOWS
#include <dirent.h>
#endif
#include <sys/stat.h>
//- string builder on arena
typedef struct StrBuf StrBuf;
struct StrBuf {
char *data;
u64 size;
u64 cap;
};
internal void strbuf_init(Arena *arena, StrBuf *b, u64 cap)
{
b->data = PushArray(arena, char, cap);
b->size = 0;
b->cap = cap;
}
internal void strbuf_fmt(StrBuf *b, const char *fmt, ...)
{
if(b->size + 1 >= b->cap) return;
va_list args;
va_start(args, fmt);
int n = vsnprintf(b->data + b->size, b->cap - b->size, fmt, args);
va_end(args);
if(n > 0) b->size += Min((u64)n, b->cap - 1 - b->size);
}
//- binary format (.dit)
// NOTE: v2 adds docs (the text heap), source links, repo settings, more bends and message y.
// v1 files still load: their structs are kept below and converted field by field.
#define DIT_MAGIC 0x54494444u // "DDIT"
#define DIT_VERSION 2u
typedef struct DitHeaderV1 DitHeaderV1;
struct DitHeaderV1 {
u32 magic;
u32 version;
u32 node_count;
u32 edge_count;
u32 section_count;
u32 member_count;
u32 next_id;
u32 default_routing;
char title[96];
};
typedef struct DitHeader DitHeader;
struct DitHeader {
DitHeaderV1 v1;
u32 text_size;
u32 doc_off;
u32 doc_len;
u32 node_size; // sizeof(DiagramNode) when written, a mismatch means another build wrote it
u32 edge_size;
u32 reserved[3];
char repo[256];
char repo_ref[64];
char repo_root[512];
};
typedef struct DiagramNodeV1 DiagramNodeV1;
struct DiagramNodeV1 {
b32 alive;
u32 id, kind, border_style;
s32 parent;
b32 collapsed, pinned, selected;
f32 x, y, w, h;
b32 manual_size;
f32 min_w, min_h;
u32 color;
s32 first_section, last_section;
u32 section_count;
char key[48], name[80], stereotype[48], tag[32], note[128];
f32 header_h;
};
typedef struct DiagramEdgeV1 DiagramEdgeV1;
struct DiagramEdgeV1 {
b32 alive;
u32 id;
s32 src, dst;
u32 kind, routing, src_port, dst_port;
s32 src_member, dst_member;
b32 selected;
u32 color;
u32 waypoint_count;
Vec2f waypoints[4];
char label[64], src_mult[16], dst_mult[16], tag[32];
};
internal b32 diagram_save_binary(Diagram *d, const char *path)
{
FILE *f = fopen(path, "wb");
if(!f) return false;
diagram_compact_text(d);
DitHeader hdr = {};
hdr.v1.magic = DIT_MAGIC;
hdr.v1.version = DIT_VERSION;
hdr.v1.node_count = d->node_count;
hdr.v1.edge_count = d->edge_count;
hdr.v1.section_count = d->section_count;
hdr.v1.member_count = d->member_count;
hdr.v1.next_id = d->next_id;
hdr.v1.default_routing = d->default_routing;
hdr.text_size = d->text_size;
hdr.doc_off = d->doc_off;
hdr.doc_len = d->doc_len;
hdr.node_size = sizeof(DiagramNode);
hdr.edge_size = sizeof(DiagramEdge);
MemCpy(hdr.v1.title, d->title, sizeof(hdr.v1.title));
MemCpy(hdr.repo, d->repo, sizeof(hdr.repo));
MemCpy(hdr.repo_ref, d->repo_ref, sizeof(hdr.repo_ref));
MemCpy(hdr.repo_root, d->repo_root, sizeof(hdr.repo_root));
fwrite(&hdr, sizeof(hdr), 1, f);
if(d->node_count) fwrite(d->nodes, sizeof(DiagramNode), d->node_count, f);
if(d->edge_count) fwrite(d->edges, sizeof(DiagramEdge), d->edge_count, f);
if(d->section_count) fwrite(d->sections, sizeof(NodeSection), d->section_count, f);
if(d->member_count) fwrite(d->members, sizeof(NodeMember), d->member_count, f);
if(d->text_size) fwrite(d->text, 1, d->text_size, f);
fclose(f);
snprintf(d->file_path, sizeof(d->file_path), "%s", path);
d->dirty = false;
return true;
}
internal b32 diagram_load_binary(Diagram *d, const char *path)
{
FILE *f = fopen(path, "rb");
if(!f) return false;
DitHeader hdr = {};
if(fread(&hdr.v1, sizeof(hdr.v1), 1, f) != 1 || hdr.v1.magic != DIT_MAGIC || (hdr.v1.version != 1 && hdr.v1.version != DIT_VERSION)) {
fclose(f);
return false;
}
b32 v1 = (hdr.v1.version == 1);
if(!v1) {
if(fread((u8 *)&hdr + sizeof(hdr.v1), sizeof(hdr) - sizeof(hdr.v1), 1, f) != 1 ||
hdr.node_size != sizeof(DiagramNode) || hdr.edge_size != sizeof(DiagramEdge) || hdr.text_size > d->text_cap) {
fclose(f);
return false;
}
}
if(hdr.v1.node_count > d->node_cap || hdr.v1.edge_count > d->edge_cap ||
hdr.v1.section_count > d->section_cap || hdr.v1.member_count > d->member_cap) {
fclose(f);
return false;
}
diagram_clear(d);
d->node_count = hdr.v1.node_count;
d->edge_count = hdr.v1.edge_count;
d->section_count = hdr.v1.section_count;
d->member_count = hdr.v1.member_count;
d->next_id = Max(hdr.v1.next_id, 1u);
d->default_routing = hdr.v1.default_routing < ROUTE_COUNT ? hdr.v1.default_routing : ROUTE_ORTHOGONAL;
MemCpy(d->title, hdr.v1.title, sizeof(d->title));
d->title[sizeof(d->title) - 1] = 0;
b32 ok = true;
if(v1) {
ScratchArena scratch = ScratchGet();
DiagramNodeV1 *nodes = PushArrayZero(scratch.arena, DiagramNodeV1, d->node_count + 1);
DiagramEdgeV1 *edges = PushArrayZero(scratch.arena, DiagramEdgeV1, d->edge_count + 1);
if(d->node_count && fread(nodes, sizeof(DiagramNodeV1), d->node_count, f) != d->node_count) ok = false;
if(d->edge_count && fread(edges, sizeof(DiagramEdgeV1), d->edge_count, f) != d->edge_count) ok = false;
for(u32 i = 0; ok && i < d->node_count; ++i) {
DiagramNodeV1 *o = &nodes[i];
DiagramNode *n = &d->nodes[i];
MemSetZero(n, sizeof(*n));
n->alive = o->alive; n->id = o->id; n->kind = o->kind < NODE_KIND_COUNT ? o->kind : NODE_STRUCT; n->border_style = o->border_style;
n->parent = o->parent; n->collapsed = o->collapsed; n->pinned = o->pinned;
n->x = o->x; n->y = o->y; n->w = o->w; n->h = o->h; n->manual_size = o->manual_size;
n->color = o->color; n->first_section = o->first_section; n->last_section = o->last_section; n->section_count = o->section_count;
MemCpy(n->key, o->key, sizeof(n->key)); MemCpy(n->name, o->name, sizeof(n->name));
MemCpy(n->stereotype, o->stereotype, sizeof(n->stereotype)); MemCpy(n->tag, o->tag, sizeof(n->tag));
MemCpy(n->note, o->note, sizeof(n->note));
}
for(u32 i = 0; ok && i < d->edge_count; ++i) {
DiagramEdgeV1 *o = &edges[i];
DiagramEdge *e = &d->edges[i];
MemSetZero(e, sizeof(*e));
e->alive = o->alive; e->id = o->id; e->src = o->src; e->dst = o->dst; e->kind = o->kind < EDGE_KIND_COUNT ? o->kind : EDGE_ASSOCIATION;
e->routing = o->routing; e->src_port = o->src_port; e->dst_port = o->dst_port;
e->src_member = o->src_member; e->dst_member = o->dst_member; e->color = o->color;
e->waypoint_count = Min(o->waypoint_count, 4u);
for(u32 w = 0; w < e->waypoint_count; ++w) e->waypoints[w] = o->waypoints[w];
MemCpy(e->label, o->label, sizeof(e->label)); MemCpy(e->src_mult, o->src_mult, sizeof(e->src_mult));
MemCpy(e->dst_mult, o->dst_mult, sizeof(e->dst_mult)); MemCpy(e->tag, o->tag, sizeof(e->tag));
}
scratch_end(&scratch);
} else {
if(d->node_count && fread(d->nodes, sizeof(DiagramNode), d->node_count, f) != d->node_count) ok = false;
if(d->edge_count && fread(d->edges, sizeof(DiagramEdge), d->edge_count, f) != d->edge_count) ok = false;
}
if(ok && d->section_count && fread(d->sections, sizeof(NodeSection), d->section_count, f) != d->section_count) ok = false;
if(ok && d->member_count && fread(d->members, sizeof(NodeMember), d->member_count, f) != d->member_count) ok = false;
if(ok && !v1) {
d->text_size = hdr.text_size;
d->doc_off = hdr.doc_off;
d->doc_len = hdr.doc_len;
if(d->text_size && fread(d->text, 1, d->text_size, f) != d->text_size) ok = false;
MemCpy(d->repo, hdr.repo, sizeof(d->repo));
MemCpy(d->repo_ref, hdr.repo_ref, sizeof(d->repo_ref));
MemCpy(d->repo_root, hdr.repo_root, sizeof(d->repo_root));
d->repo[sizeof(d->repo) - 1] = d->repo_ref[sizeof(d->repo_ref) - 1] = d->repo_root[sizeof(d->repo_root) - 1] = 0;
}
fclose(f);
if(!ok) {
diagram_clear(d);
return false;
}
for(u32 i = 0; i < d->node_count; ++i) {
d->nodes[i].selected = false;
if(d->nodes[i].kind >= NODE_KIND_COUNT) d->nodes[i].kind = NODE_STRUCT;
}
for(u32 i = 0; i < d->edge_count; ++i) {
d->edges[i].selected = false;
if(d->edges[i].waypoint_count > DIAGRAM_MAX_WAYPOINTS) d->edges[i].waypoint_count = 0;
if(d->edges[i].kind >= EDGE_KIND_COUNT) d->edges[i].kind = EDGE_ASSOCIATION;
}
d->live_nodes = 0;
d->live_edges = 0;
for(u32 i = 0; i < d->node_count; ++i) d->live_nodes += (d->nodes[i].alive != 0);
for(u32 i = 0; i < d->edge_count; ++i) d->live_edges += (d->edges[i].alive != 0);
diagram_measure_all(d);
diagram_fit_lifelines(d);
diagram_rebuild_tags(d);
snprintf(d->file_path, sizeof(d->file_path), "%s", path);
d->dirty = false;
++d->version;
return true;
}
//- human-readable DSL (.dit.txt)
// NOTE: quoted strings escape \" and \\ only, any other backslash is literal (windows paths)
internal void dsl_emit_quoted(StrBuf *b, const char *s)
{
strbuf_fmt(b, "\"");
for(; *s; ++s) {
if(*s == '"' || *s == '\\') strbuf_fmt(b, "\\%c", *s);
else if(*s == '\n') strbuf_fmt(b, "\\n");
else strbuf_fmt(b, "%c", *s);
}
strbuf_fmt(b, "\"");
}
internal void dsl_indent(StrBuf *b, u32 indent)
{
for(u32 i = 0; i < indent; ++i) strbuf_fmt(b, " ");
}
// NOTE: doc """ block: one text line per line, indented one level deeper than the keyword. a line
// holding """ gets it escaped so the block can't end early
internal void dsl_emit_doc(StrBuf *b, String8 doc, u32 indent)
{
if(doc.size == 0) return;
dsl_indent(b, indent);
strbuf_fmt(b, "doc \"\"\"\n");
u64 start = 0;
for(u64 i = 0; i <= doc.size; ++i) {
if(i < doc.size && doc.data[i] != '\n') continue;
String8 line = ToString8Size(doc.data + start, i - start);
if(line.size && line.data[line.size - 1] == '\r') --line.size;
if(line.size) dsl_indent(b, indent + 1);
for(u64 c = 0; c < line.size; ++c) {
if(c + 2 < line.size && line.data[c] == '"' && line.data[c + 1] == '"' && line.data[c + 2] == '"') {
strbuf_fmt(b, "\\\"\"\"");
c += 2;
} else {
strbuf_fmt(b, "%c", line.data[c]);
}
}
strbuf_fmt(b, "\n");
start = i + 1;
}
dsl_indent(b, indent);
strbuf_fmt(b, "\"\"\"\n");
}
// NOTE: include == NULL emits every node, otherwise only flagged ones (a copy of the selection)
internal void dsl_emit_node(StrBuf *b, Diagram *d, s32 idx, u32 indent, const b8 *include)
{
DiagramNode *n = &d->nodes[idx];
dsl_indent(b, indent);
strbuf_fmt(b, "%s ", node_kind_name(n->kind));
dsl_emit_quoted(b, n->name);
strbuf_fmt(b, " id=%s", n->key);
if(n->stereotype[0]) { strbuf_fmt(b, " stereo="); dsl_emit_quoted(b, n->stereotype); }
if(n->tag[0]) strbuf_fmt(b, " tag=%s", n->tag);
if(n->color) strbuf_fmt(b, " color=#%08X", n->color);
if(n->link[0]) { strbuf_fmt(b, " link="); dsl_emit_quoted(b, n->link); }
strbuf_fmt(b, " x=%.0f y=%.0f", n->x, n->y);
if(n->manual_size || n->kind == NODE_MODULE) strbuf_fmt(b, " w=%.0f h=%.0f", n->w, n->h);
if(n->collapsed) strbuf_fmt(b, " collapsed=1");
if(n->pinned) strbuf_fmt(b, " pinned=1");
b32 has_children = false;
for(u32 j = 0; j < d->node_count; ++j) {
if(d->nodes[j].alive && d->nodes[j].parent == idx && (!include || include[j])) { has_children = true; break; }
}
if(n->first_section < 0 && !n->note[0] && !n->doc_len && !has_children) {
strbuf_fmt(b, "\n");
return;
}
strbuf_fmt(b, " {\n");
if(n->note[0]) {
dsl_indent(b, indent + 1);
strbuf_fmt(b, "note ");
dsl_emit_quoted(b, n->note);
strbuf_fmt(b, "\n");
}
dsl_emit_doc(b, diagram_doc(d, n->doc_off, n->doc_len), indent + 1);
for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) {
NodeSection *sec = &d->sections[s];
dsl_indent(b, indent + 1);
strbuf_fmt(b, "section ");
dsl_emit_quoted(b, sec->title);
strbuf_fmt(b, "%s {\n", sec->collapsed ? " collapsed=1" : "");
for(s32 m = sec->first_member; m >= 0; m = d->members[m].next) {
NodeMember *mem = &d->members[m];
dsl_indent(b, indent + 2);
if(mem->visibility) strbuf_fmt(b, "%c ", mem->visibility);
strbuf_fmt(b, "%s", mem->name);
if(mem->type[0]) strbuf_fmt(b, " : %s", mem->type);
if(mem->badge[0]) strbuf_fmt(b, " [%s]", mem->badge);
strbuf_fmt(b, "\n");
}
dsl_indent(b, indent + 1);
strbuf_fmt(b, "}\n");
}
if(has_children) {
for(u32 j = 0; j < d->node_count; ++j) {
if(d->nodes[j].alive && d->nodes[j].parent == idx && (!include || include[j])) dsl_emit_node(b, d, (s32)j, indent + 1, include);
}
}
dsl_indent(b, indent);
strbuf_fmt(b, "}\n");
}
internal void dsl_emit_edge(StrBuf *b, Diagram *d, s32 index)
{
DiagramEdge *e = &d->edges[index];
strbuf_fmt(b, "%s %s %s", d->nodes[e->src].key, edge_kind_symbol(e->kind), d->nodes[e->dst].key);
if(e->label[0]) { strbuf_fmt(b, " : "); dsl_emit_quoted(b, e->label); }
if(e->src_mult[0] || e->dst_mult[0]) strbuf_fmt(b, " [%s -> %s]", e->src_mult, e->dst_mult);
if(e->routing != ROUTE_AUTO) strbuf_fmt(b, " route=%s", edge_routing_name(e->routing));
if(e->src_port != PORT_AUTO) strbuf_fmt(b, " from=%s", port_side_name(e->src_port));
if(e->dst_port != PORT_AUTO) strbuf_fmt(b, " to=%s", port_side_name(e->dst_port));
if(e->tag[0]) strbuf_fmt(b, " tag=%s", e->tag);
if(e->color) strbuf_fmt(b, " color=#%08X", e->color);
if(diagram_edge_is_message(d, index)) strbuf_fmt(b, " y=%.0f", e->msg_y);
if(e->waypoint_count) {
strbuf_fmt(b, " via=");
for(u32 w = 0; w < e->waypoint_count; ++w) strbuf_fmt(b, "%s%.0f,%.0f", w ? ";" : "", e->waypoints[w].x, e->waypoints[w].y);
}
String8 doc = diagram_doc(d, e->doc_off, e->doc_len);
if(doc.size) {
strbuf_fmt(b, " {\n");
dsl_emit_doc(b, doc, 1);
strbuf_fmt(b, "}\n");
} else {
strbuf_fmt(b, "\n");
}
}
internal String8 dsl_emit(Arena *arena, Diagram *d, const b8 *include, b32 header)
{
StrBuf b;
strbuf_init(arena, &b, MiB(1) + (u64)d->text_size * 2);
if(header) {
strbuf_fmt(&b, "diagram ");
dsl_emit_quoted(&b, d->title);
strbuf_fmt(&b, " routing=%s", edge_routing_name(d->default_routing));
if(d->repo[0]) { strbuf_fmt(&b, " repo="); dsl_emit_quoted(&b, d->repo); }
if(d->repo_ref[0]) { strbuf_fmt(&b, " ref="); dsl_emit_quoted(&b, d->repo_ref); }
if(d->repo_root[0]) { strbuf_fmt(&b, " root="); dsl_emit_quoted(&b, d->repo_root); }
strbuf_fmt(&b, "\n");
dsl_emit_doc(&b, diagram_doc(d, d->doc_off, d->doc_len), 0);
strbuf_fmt(&b, "\n");
}
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || (include && !include[i])) continue;
b32 top = (n->parent < 0) || (include && !include[n->parent]);
if(top) dsl_emit_node(&b, d, (s32)i, 0, include);
}
b32 first_edge = true;
for(u32 i = 0; i < d->edge_count; ++i) {
DiagramEdge *e = &d->edges[i];
if(!e->alive || (include && (!include[e->src] || !include[e->dst]))) continue;
if(first_edge) { strbuf_fmt(&b, "\n"); first_edge = false; }
dsl_emit_edge(&b, d, (s32)i);
}
return ToString8Size((u8 *)b.data, b.size);
}
internal String8 diagram_to_dsl(Arena *arena, Diagram *d)
{
return dsl_emit(arena, d, NULL, true);
}
// NOTE: the selected nodes, everything inside selected modules, and the edges among them. what the
// clipboard holds, so pasting into a text editor shows plain DSL
internal String8 diagram_selection_to_dsl(Arena *arena, Diagram *d, s32 also_node, u32 *out_nodes)
{
b8 *include = PushArrayZero(arena, b8, d->node_count + 1);
u32 count = 0;
for(u32 i = 0; i < d->node_count; ++i) {
if(d->nodes[i].alive && (d->nodes[i].selected || (s32)i == also_node)) include[i] = 1;
}
// children of included modules come along (a few passes cover nesting)
for(u32 pass = 0; pass < 8; ++pass) {
b32 changed = false;
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(n->alive && !include[i] && n->parent >= 0 && include[n->parent]) { include[i] = 1; changed = true; }
}
if(!changed) break;
}
for(u32 i = 0; i < d->node_count; ++i) count += include[i];
if(out_nodes) *out_nodes = count;
if(!count) return str8_zero();
String8 body = dsl_emit(arena, d, include, false);
// NOTE: the marker line tells paste this is ours, a text editor just sees a comment
String8 marker = str8((char *)"# design-it selection\n");
u8 *out = PushArray(arena, u8, marker.size + body.size + 1);
MemCpy(out, marker.data, marker.size);
MemCpy(out + marker.size, body.data, body.size);
out[marker.size + body.size] = 0;
return ToString8Size(out, marker.size + body.size);
}
internal const char *dsl_skip_ws(const char *p) { while(*p == ' ' || *p == '\t' || *p == '\r') ++p; return p; }
internal const char *dsl_read_quoted(const char *p, char *out, u32 cap)
{
p = dsl_skip_ws(p);
u32 n = 0;
if(*p == '"') {
++p;
while(*p && *p != '"' && *p != '\n') {
char c = *p;
if(c == '\\' && (p[1] == '"' || p[1] == '\\')) { c = p[1]; ++p; }
else if(c == '\\' && p[1] == 'n') { c = '\n'; ++p; }
if(n + 1 < cap) out[n++] = c;
++p;
}
if(*p == '"') ++p;
} else {
while(*p && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r' && *p != '{' && *p != '}') {
if(n + 1 < cap) out[n++] = *p;
++p;
}
}
out[n] = 0;
return p;
}
internal s32 dsl_match_node_kind(const char *word)
{
for(u32 i = 0; i < NODE_KIND_COUNT; ++i) if(!strcasecmp(word, diagram_node_kind_names[i])) return (s32)i;
if(!strcasecmp(word, "participant")) return NODE_LIFELINE;
return -1;
}
internal s32 dsl_match_edge_sym(const char *sym)
{
for(u32 i = 0; i < EDGE_KIND_COUNT; ++i) if(!strcmp(sym, diagram_edge_kind_symbols[i])) return (s32)i;
return -1;
}
internal u32 dsl_parse_color(const char *tok)
{
const char *hx = (tok[0] == '#') ? tok + 1 : tok;
u32 c = (u32)strtoul(hx, NULL, 16);
if(strlen(hx) == 6) c = (c << 8) | 0xFF;
return c;
}
internal u32 dsl_parse_port(const char *tok)
{
for(u32 i = 0; i < PORT_COUNT; ++i) if(!strcasecmp(tok, diagram_port_side_names[i])) return i;
if(!strcasecmp(tok, "n") || !strcasecmp(tok, "top")) return PORT_NORTH;
if(!strcasecmp(tok, "s") || !strcasecmp(tok, "bottom")) return PORT_SOUTH;
if(!strcasecmp(tok, "e") || !strcasecmp(tok, "right")) return PORT_EAST;
if(!strcasecmp(tok, "w") || !strcasecmp(tok, "left")) return PORT_WEST;
return PORT_AUTO;
}
// NOTE: next key=value pair on a line: false at the end or at a '{'. values may be quoted
internal b32 dsl_next_attr(const char **at, char *key, u32 key_cap, char *value, u32 value_cap, b32 *brace)
{
const char *q = *at;
for(;;) {
q = dsl_skip_ws(q);
if(!*q || *q == '\n') { *at = q; return false; }
if(*q == '{') { if(brace) *brace = true; *at = q + 1; return false; }
const char *eq = q;
while(*eq && *eq != '=' && *eq != ' ' && *eq != '\t' && *eq != '{') ++eq;
if(*eq == '=' && eq > q && (u32)(eq - q) < key_cap) {
MemCpy(key, q, (u64)(eq - q));
key[eq - q] = 0;
*at = dsl_read_quoted(eq + 1, value, value_cap);
return true;
}
// not an attribute: skip the word (or the quoted string)
if(*q == '"') {
char skip[8];
q = dsl_read_quoted(q, skip, sizeof(skip));
} else {
while(*q && *q != ' ' && *q != '\t' && *q != '{') ++q;
}
}
}
typedef struct DslKeyMap DslKeyMap;
struct DslKeyMap {
char key[48];
s32 node;
};
typedef enum DslDocTarget {
DSL_DOC_NONE,
DSL_DOC_DIAGRAM,
DSL_DOC_NODE,
DSL_DOC_EDGE,
} DslDocTarget;
// NOTE: append = paste: nothing is cleared, the title / repo / diagram doc are left alone, keys in the
// text map to the nodes this text creates (never to existing nodes with the same key), and new nodes
// whose key is taken get a fresh one
internal b32 dsl_parse(Diagram *d, String8 text, b32 append, b32 *out_has_positions)
{
ScratchArena scratch = ScratchGet();
if(!append) diagram_clear(d);
s32 node_stack[16];
u32 node_depth = 0;
s32 cur_section = -1;
s32 cur_edge = -1;
b32 has_positions = false;
u32 created = 0;
DslKeyMap *map = PushArray(scratch.arena, DslKeyMap, DIAGRAM_MAX_NODES);
u32 map_count = 0;
u32 doc_target = DSL_DOC_NONE;
s32 doc_index = -1;
u64 doc_cap = Min(text.size + 16, (u64)DIAGRAM_TEXT_CAP);
char *doc_raw = PushArray(scratch.arena, char, doc_cap);
u64 doc_size = 0;
const char *at = (const char *)text.data;
const char *end = at + text.size;
while(at < end) {
const char *line_start = at;
while(at < end && *at != '\n') ++at;
u64 len = (u64)(at - line_start);
if(at < end && *at == '\n') ++at;
//- inside a doc """ block: raw lines until the closing """
if(doc_target != DSL_DOC_NONE) {
const char *t = line_start;
while(t < line_start + len && (*t == ' ' || *t == '\t')) ++t;
if(line_start + len - t >= 3 && t[0] == '"' && t[1] == '"' && t[2] == '"') {
// strip the closing line's indent (plus one level) from every line, unescape \"""
u64 indent = (u64)(t - line_start) + 2;
char *clean = PushArray(scratch.arena, char, doc_size + 1);
u64 size = 0;
u64 ls = 0;
for(u64 i = 0; i <= doc_size; ++i) {
if(i < doc_size && doc_raw[i] != '\n') continue;
u64 s = ls, strip = 0;
while(s < i && strip < indent && (doc_raw[s] == ' ' || doc_raw[s] == '\t')) { ++s; ++strip; }
for(u64 c = s; c < i; ++c) {
if(c + 3 < i && doc_raw[c] == '\\' && doc_raw[c + 1] == '"' && doc_raw[c + 2] == '"' && doc_raw[c + 3] == '"') continue;
clean[size++] = doc_raw[c];
}
if(i < doc_size) clean[size++] = '\n';
ls = i + 1;
}
// NOTE: leading blank lines are dropped, trailing ones by diagram_set_doc
u64 skip = 0;
while(skip < size && clean[skip] == '\n') ++skip;
if(doc_target == DSL_DOC_DIAGRAM && !append) diagram_set_doc(d, &d->doc_off, &d->doc_len, clean + skip, size - skip);
if(doc_target == DSL_DOC_NODE && doc_index >= 0) diagram_set_doc(d, &d->nodes[doc_index].doc_off, &d->nodes[doc_index].doc_len, clean + skip, size - skip);
if(doc_target == DSL_DOC_EDGE && doc_index >= 0) diagram_set_doc(d, &d->edges[doc_index].doc_off, &d->edges[doc_index].doc_len, clean + skip, size - skip);
doc_target = DSL_DOC_NONE;
doc_size = 0;
} else if(doc_size + len + 1 < doc_cap) {
MemCpy(doc_raw + doc_size, line_start, len);
doc_size += len;
doc_raw[doc_size++] = '\n';
}
continue;
}
char line[1024];
u64 copy = Min(len, (u64)sizeof(line) - 1);
MemCpy(line, line_start, copy);
line[copy] = 0;
const char *p = dsl_skip_ws(line);
if(!*p || *p == '#' || (p[0] == '/' && p[1] == '/')) continue;
if(*p == '}') {
if(cur_section >= 0) cur_section = -1;
else if(cur_edge != -1) cur_edge = -1;
else if(node_depth > 0) --node_depth;
continue;
}
// inside a section: parse member line "[vis] name [: type] [[badge]]"
if(cur_section >= 0) {
char vis = 0;
if((*p == '+' || *p == '-' || *p == '#' || *p == '~' || *p == '@' || *p == '*') && (p[1] == ' ' || p[1] == '\t')) {
vis = *p;
p = dsl_skip_ws(p + 1);
}
char name[64] = {}, type[80] = {}, badge[24] = {};
char work[384];
snprintf(work, sizeof(work), "%s", p);
// strip trailing [badge]
char *lb = strrchr(work, '[');
char *rb = lb ? strchr(lb, ']') : NULL;
if(lb && rb) {
*lb = 0;
*rb = 0;
snprintf(badge, sizeof(badge), "%s", lb + 1);
}
char *colon = strchr(work, ':');
if(colon) {
*colon = 0;
const char *ts = dsl_skip_ws(colon + 1);
snprintf(type, sizeof(type), "%s", ts);
u32 tl = (u32)strlen(type);
while(tl > 0 && (type[tl - 1] == ' ' || type[tl - 1] == '\t')) type[--tl] = 0;
}
snprintf(name, sizeof(name), "%s", work);
u32 nl = (u32)strlen(name);
while(nl > 0 && (name[nl - 1] == ' ' || name[nl - 1] == '\t')) name[--nl] = 0;
if(name[0]) diagram_add_member(d, cur_section, vis, name, type, badge);
continue;
}
char first[64] = {};
const char *after = dsl_read_quoted(p, first, sizeof(first));
//- doc: a """ block, or one quoted line (\n for breaks)
if(!strcmp(first, "doc")) {
const char *q = dsl_skip_ws(after);
u32 target = DSL_DOC_DIAGRAM;
s32 index = -1;
if(cur_edge != -1) { target = DSL_DOC_EDGE; index = cur_edge; } // -2: the edge was dropped
else if(node_depth > 0) { target = DSL_DOC_NODE; index = node_stack[node_depth - 1]; }
if(q[0] == '"' && q[1] == '"' && q[2] == '"') {
doc_target = target;
doc_index = index;
doc_size = 0;
} else if(*q == '"') {
char one[1024];
dsl_read_quoted(q, one, sizeof(one));
if(target == DSL_DOC_DIAGRAM && !append) diagram_set_doc(d, &d->doc_off, &d->doc_len, one, strlen(one));
if(target == DSL_DOC_NODE && index >= 0) diagram_set_doc(d, &d->nodes[index].doc_off, &d->nodes[index].doc_len, one, strlen(one));
if(target == DSL_DOC_EDGE && index >= 0) diagram_set_doc(d, &d->edges[index].doc_off, &d->edges[index].doc_len, one, strlen(one));
}
continue;
}
if(!strcmp(first, "diagram") && node_depth == 0) {
char title[96] = {};
const char *q = dsl_read_quoted(after, title, sizeof(title));
if(append) continue;
snprintf(d->title, sizeof(d->title), "%s", title);
char key[32], value[512];
while(dsl_next_attr(&q, key, sizeof(key), value, sizeof(value), NULL)) {
if(!strcmp(key, "routing")) {
for(u32 i = 0; i < ROUTE_COUNT; ++i) if(!strcasecmp(value, diagram_edge_routing_names[i])) d->default_routing = i;
} else if(!strcmp(key, "repo")) snprintf(d->repo, sizeof(d->repo), "%s", value);
else if(!strcmp(key, "ref")) snprintf(d->repo_ref, sizeof(d->repo_ref), "%s", value);
else if(!strcmp(key, "root")) snprintf(d->repo_root, sizeof(d->repo_root), "%s", value);
}
continue;
}
if(!strcmp(first, "section") && node_depth > 0) {
char stitle[40] = {};
const char *q = dsl_read_quoted(after, stitle, sizeof(stitle));
cur_section = diagram_add_section(d, node_stack[node_depth - 1], stitle);
char key[32], value[64];
while(cur_section >= 0 && dsl_next_attr(&q, key, sizeof(key), value, sizeof(value), NULL)) {
if(!strcmp(key, "collapsed")) d->sections[cur_section].collapsed = atoi(value) != 0;
}
continue;
}
if(!strcmp(first, "note") && node_depth > 0 && *dsl_skip_ws(after) == '"') {
DiagramNode *cur = &d->nodes[node_stack[node_depth - 1]];
dsl_read_quoted(after, cur->note, sizeof(cur->note));
continue;
}
s32 nkind = dsl_match_node_kind(first);
if(nkind >= 0) {
char name[80] = {};
after = dsl_read_quoted(after, name, sizeof(name));
s32 idx = diagram_add_node(d, (NodeKind)nkind, name, 40.0f + (f32)created * 32.0f, 40.0f);
if(idx < 0) continue;
++created;
DiagramNode *nd = &d->nodes[idx];
if(node_depth > 0) nd->parent = node_stack[node_depth - 1];
b32 open_brace = false;
const char *q = after;
char key[32], tok[512];
while(dsl_next_attr(&q, key, sizeof(key), tok, sizeof(tok), &open_brace)) {
if(!strcmp(key, "id")) {
if(append) {
if(map_count < DIAGRAM_MAX_NODES) {
snprintf(map[map_count].key, sizeof(map[map_count].key), "%s", tok);
map[map_count++].node = idx;
}
s32 other = diagram_find_node_by_key(d, tok);
if(other < 0 || other == idx) snprintf(nd->key, sizeof(nd->key), "%s", tok);
else {
nd->key[0] = 0;
diagram_make_key(d, nd->key, sizeof(nd->key), tok, nd->id);
}
} else {
snprintf(nd->key, sizeof(nd->key), "%s", tok);
}
}
else if(!strcmp(key, "stereo")) snprintf(nd->stereotype, sizeof(nd->stereotype), "%s", tok);
else if(!strcmp(key, "tag")) snprintf(nd->tag, sizeof(nd->tag), "%s", tok);
else if(!strcmp(key, "link")) snprintf(nd->link, sizeof(nd->link), "%s", tok);
else if(!strcmp(key, "x")) { nd->x = (f32)atof(tok); has_positions = true; }
else if(!strcmp(key, "y")) { nd->y = (f32)atof(tok); has_positions = true; }
else if(!strcmp(key, "w")) { nd->w = (f32)atof(tok); nd->manual_size = true; }
else if(!strcmp(key, "h")) { nd->h = (f32)atof(tok); nd->manual_size = true; }
else if(!strcmp(key, "collapsed")) nd->collapsed = atoi(tok) != 0;
else if(!strcmp(key, "pinned")) nd->pinned = atoi(tok) != 0;
else if(!strcmp(key, "color")) nd->color = dsl_parse_color(tok);
}
// NOTE: a lifeline's height is derived from its messages, w / h only pin the width
if(node_kind_is_lifeline(nd->kind)) nd->manual_size = false;
if(open_brace && node_depth < ArrayCount(node_stack)) {
node_stack[node_depth++] = idx;
}
continue;
}
// otherwise try edge: src_key <sym> dst_key [: "label"] [m1 -> m2] [key=value ...] [{ doc }]
char sym[16] = {}, dst_key[64] = {};
const char *p2 = dsl_read_quoted(after, sym, sizeof(sym));
s32 ekind = dsl_match_edge_sym(sym);
if(ekind >= 0) {
const char *p3 = dsl_read_quoted(p2, dst_key, sizeof(dst_key));
s32 src = -1, dst = -1;
if(append) {
for(u32 i = 0; i < map_count; ++i) {
if(src < 0 && !strcmp(map[i].key, first)) src = map[i].node;
if(dst < 0 && !strcmp(map[i].key, dst_key)) dst = map[i].node;
}
} else {
src = diagram_find_node_by_key(d, first);
dst = diagram_find_node_by_key(d, dst_key);
}
if(src >= 0 && dst >= 0) {
s32 ei = diagram_add_edge(d, src, dst, (EdgeKind)ekind, "");
if(ei >= 0) {
DiagramEdge *ed = &d->edges[ei];
const char *q = dsl_skip_ws(p3);
if(*q == ':') q = dsl_read_quoted(q + 1, ed->label, sizeof(ed->label));
q = dsl_skip_ws(q);
if(*q == '[') {
const char *rb = strchr(q, ']');
if(rb) {
char mbuf[64] = {};
u64 ml = Min((u64)(rb - q - 1), (u64)sizeof(mbuf) - 1);
MemCpy(mbuf, q + 1, ml);
char *arr = strstr(mbuf, "->");
if(arr) {
*arr = 0;
snprintf(ed->src_mult, sizeof(ed->src_mult), "%s", dsl_skip_ws(mbuf));
snprintf(ed->dst_mult, sizeof(ed->dst_mult), "%s", dsl_skip_ws(arr + 2));
u32 sl = (u32)strlen(ed->src_mult);
while(sl > 0 && ed->src_mult[sl - 1] == ' ') ed->src_mult[--sl] = 0;
}
q = rb + 1;
}
}
b32 open_brace = false;
char key[32], tok[512];
while(dsl_next_attr(&q, key, sizeof(key), tok, sizeof(tok), &open_brace)) {
if(!strcmp(key, "route")) {
for(u32 i = 0; i < ROUTE_COUNT; ++i) if(!strcasecmp(tok, diagram_edge_routing_names[i])) ed->routing = i;
}
else if(!strcmp(key, "tag")) snprintf(ed->tag, sizeof(ed->tag), "%s", tok);
else if(!strcmp(key, "color")) ed->color = dsl_parse_color(tok);
else if(!strcmp(key, "from")) ed->src_port = dsl_parse_port(tok);
else if(!strcmp(key, "to")) ed->dst_port = dsl_parse_port(tok);
else if(!strcmp(key, "y")) ed->msg_y = (f32)atof(tok);
else if(!strcmp(key, "via")) {
ed->waypoint_count = 0;
const char *v = tok;
while(*v && ed->waypoint_count < DIAGRAM_MAX_WAYPOINTS) {
char *next = NULL;
f32 x = strtof(v, &next);
if(!next || next == v || *next != ',') break;
v = next + 1;
f32 y = strtof(v, &next);
if(!next || next == v) break;
ed->waypoints[ed->waypoint_count++] = Vec2f{x, y};
v = next;
while(*v == ';' || *v == ' ') ++v;
}
}
}
if(open_brace) cur_edge = ei;
}
} else {
// NOTE: an edge to a missing node still may own a { doc } body, skip it
const char *q = p3;
b32 open_brace = false;
char key[32], tok[64];
while(dsl_next_attr(&q, key, sizeof(key), tok, sizeof(tok), &open_brace)) {}
if(open_brace) cur_edge = -2;
}
}
}
// NOTE: an unterminated """ block keeps what it had
if(doc_target != DSL_DOC_NONE && doc_size) {
if(doc_target == DSL_DOC_NODE && doc_index >= 0) diagram_set_doc(d, &d->nodes[doc_index].doc_off, &d->nodes[doc_index].doc_len, doc_raw, doc_size);
if(doc_target == DSL_DOC_EDGE && doc_index >= 0) diagram_set_doc(d, &d->edges[doc_index].doc_off, &d->edges[doc_index].doc_len, doc_raw, doc_size);
if(doc_target == DSL_DOC_DIAGRAM && !append) diagram_set_doc(d, &d->doc_off, &d->doc_len, doc_raw, doc_size);
}
// NOTE: messages without y= already got one in file order from diagram_add_edge
diagram_measure_all(d);
if(out_has_positions) *out_has_positions = has_positions;
scratch_end(&scratch);
return created > 0;
}
internal b32 diagram_from_dsl(Diagram *d, String8 text)
{
b32 has_positions = false;
dsl_parse(d, text, false, &has_positions);
if(!has_positions && d->live_nodes > 0) diagram_layout_layered(d, false);
else diagram_fit_containers(d);
diagram_fit_lifelines(d);
diagram_rebuild_tags(d);
d->dirty = false;
return d->live_nodes > 0;
}
// NOTE: paste. new nodes keep the positions in the text, the caller moves them where they belong
internal b32 diagram_append_dsl(Diagram *d, String8 text)
{
b32 ok = dsl_parse(d, text, true, NULL);
diagram_fit_containers(d);
diagram_fit_lifelines(d);
diagram_rebuild_tags(d);
d->dirty = true;
++d->version;
return ok;
}
internal b32 diagram_save_file(Diagram *d, const char *path)
{
u64 len = strlen(path);
if(len >= 4 && !strcmp(path + len - 4, ".dit")) {
return diagram_save_binary(d, path);
}
ScratchArena scratch = ScratchGet();
String8 text = diagram_to_dsl(scratch.arena, d);
FILE *f = fopen(path, "wb");
if(!f) { scratch_end(&scratch); return false; }
fwrite(text.data, 1, text.size, f);
fclose(f);
snprintf(d->file_path, sizeof(d->file_path), "%s", path);
d->dirty = false;
scratch_end(&scratch);
return true;
}
internal b32 diagram_load_file(Diagram *d, const char *path)
{
u64 len = strlen(path);
if(len >= 4 && !strcmp(path + len - 4, ".dit")) {
return diagram_load_binary(d, path);
}
ScratchArena scratch = ScratchGet();
String8 text = FileLoad(scratch.arena, str8((char *)path));
if(text.size == 0) { scratch_end(&scratch); return false; }
// NOTE: .dit.txt, mermaid (.mmd) or plantuml (.puml), by extension and then by content
b32 ok = diagram_import_text(d, text, path);
if(ok) snprintf(d->file_path, sizeof(d->file_path), "%s", path);
scratch_end(&scratch);
return ok;
}
//- native vector SVG export
internal void svg_color(char *out, u32 cap, u32 rgba)
{
snprintf(out, cap, "#%06X", (rgba >> 8) & 0xFFFFFFu);
}
internal void svg_escape(StrBuf *b, const char *s)
{
for(; *s; ++s) {
if(*s == '&') strbuf_fmt(b, "&");
else if(*s == '<') strbuf_fmt(b, "<");
else if(*s == '>') strbuf_fmt(b, ">");
else if(*s == '"') strbuf_fmt(b, """);
else strbuf_fmt(b, "%c", *s);
}
}
internal void svg_escape_n(StrBuf *b, String8 s)
{
for(u64 i = 0; i < s.size; ++i) {
char c = (char)s.data[i];
if(c == '&') strbuf_fmt(b, "&");
else if(c == '<') strbuf_fmt(b, "<");
else if(c == '>') strbuf_fmt(b, ">");
else if(c == '"') strbuf_fmt(b, """);
else strbuf_fmt(b, "%c", c);
}
}
internal b32 diagram_export_svg(Diagram *d, const char *path, const u32 *colors)
{
ScratchArena scratch = ScratchGet();
StrBuf b;
strbuf_init(scratch.arena, &b, MiB(4));
Rect bounds = diagram_bounds(d);
f32 pad = 48.0f;
f32 vx = bounds.x0 - pad, vy = bounds.y0 - pad;
f32 vw = Max(rect_w(bounds) + pad * 2.0f, 320.0f);
f32 vh = Max(rect_h(bounds) + pad * 2.0f, 200.0f);
char c_bg[16], c_panel[16], c_edge[16], c_hdr[16], c_txt[16], c_dim[16], c_acc[16];
svg_color(c_bg, sizeof(c_bg), colors[0]); // BG
svg_color(c_panel, sizeof(c_panel), colors[1]); // PANEL
svg_color(c_edge, sizeof(c_edge), colors[3]); // FOCUS_EDGE
svg_color(c_hdr, sizeof(c_hdr), colors[5]); // TAB_ACTIVE
svg_color(c_txt, sizeof(c_txt), colors[10]); // TEXT
svg_color(c_dim, sizeof(c_dim), colors[11]); // TEXT_DIM
svg_color(c_acc, sizeof(c_acc), colors[13]); // ACCENT
strbuf_fmt(&b, "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"%.1f %.1f %.1f %.1f\" width=\"%.0f\" height=\"%.0f\">\n",
vx, vy, vw, vh, vw, vh);
strbuf_fmt(&b, "<rect x=\"%.1f\" y=\"%.1f\" width=\"%.1f\" height=\"%.1f\" fill=\"%s\"/>\n", vx, vy, vw, vh, c_bg);
strbuf_fmt(&b, "<style>text{font-family:'JetBrains Mono','Noto Sans Mono',monospace;}</style>\n");
// 1. Containers behind
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->kind != NODE_MODULE || diagram_node_hidden(d, (s32)i)) continue;
char stroke[16];
svg_color(stroke, sizeof(stroke), n->color ? n->color : colors[3]);
strbuf_fmt(&b, "<rect x=\"%.1f\" y=\"%.1f\" width=\"%.1f\" height=\"%.1f\" fill=\"%s\" fill-opacity=\"0.35\" stroke=\"%s\" stroke-dasharray=\"6 4\" stroke-width=\"1.2\"/>\n",
n->x, n->y, n->w, n->h, c_panel, stroke);
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"12\" font-weight=\"600\">", n->x + 10.0f, n->y + 19.0f, c_txt);
svg_escape(&b, n->name);
strbuf_fmt(&b, "</text>\n");
}
// 2. Edges
EdgePath ep;
for(u32 i = 0; i < d->edge_count; ++i) {
DiagramEdge *e = &d->edges[i];
if(!e->alive || diagram_edge_hidden(d, (s32)i) || !diagram_edge_route(d, (s32)i, &ep)) continue;
char ec[16];
svg_color(ec, sizeof(ec), e->color ? e->color : ((e->kind == EDGE_DATAFLOW) ? colors[13] : colors[11]));
b32 dashed = (e->kind == EDGE_DEPENDENCY || e->kind == EDGE_IMPLEMENTS || e->kind == EDGE_ASYNC || e->kind == EDGE_REPLY);
f32 sw = (e->kind == EDGE_DATAFLOW) ? 2.2f : 1.4f;
if(ep.routing == ROUTE_BEZIER) {
strbuf_fmt(&b, "<path d=\"M %.1f %.1f C %.1f %.1f %.1f %.1f %.1f %.1f\" fill=\"none\" stroke=\"%s\" stroke-width=\"%.1f\"%s/>\n",
ep.points[0].x, ep.points[0].y, ep.c0.x, ep.c0.y, ep.c1.x, ep.c1.y, ep.points[1].x, ep.points[1].y,
ec, sw, dashed ? " stroke-dasharray=\"6 4\"" : "");
} else {
strbuf_fmt(&b, "<polyline points=\"");
for(u32 p = 0; p < ep.point_count; ++p) strbuf_fmt(&b, "%.1f,%.1f ", ep.points[p].x, ep.points[p].y);
strbuf_fmt(&b, "\" fill=\"none\" stroke=\"%s\" stroke-width=\"%.1f\"%s/>\n", ec, sw, dashed ? " stroke-dasharray=\"6 4\"" : "");
}
// Target arrowhead
if(e->kind != EDGE_LINK) {
Vec2f tip = ep.points[ep.point_count - 1];
Vec2f dir = ep.dst_dir;
Vec2f side = {-dir.y, dir.x};
f32 len = 11.0f, hw = 5.5f;
Vec2f b1 = {tip.x - dir.x * len + side.x * hw, tip.y - dir.y * len + side.y * hw};
Vec2f b2 = {tip.x - dir.x * len - side.x * hw, tip.y - dir.y * len - side.y * hw};
b32 hollow = (e->kind == EDGE_INHERITANCE || e->kind == EDGE_IMPLEMENTS);
b32 open = (e->kind == EDGE_REPLY || e->kind == EDGE_ASSOCIATION || e->kind == EDGE_DEPENDENCY || e->kind == EDGE_BIDIR);
if(open) {
strbuf_fmt(&b, "<polyline points=\"%.1f,%.1f %.1f,%.1f %.1f,%.1f\" fill=\"none\" stroke=\"%s\" stroke-width=\"1.4\"/>\n",
b1.x, b1.y, tip.x, tip.y, b2.x, b2.y, ec);
} else {
strbuf_fmt(&b, "<polygon points=\"%.1f,%.1f %.1f,%.1f %.1f,%.1f\" fill=\"%s\" stroke=\"%s\" stroke-width=\"1.2\"/>\n",
tip.x, tip.y, b1.x, b1.y, b2.x, b2.y, hollow ? c_bg : ec, ec);
}
}
if(e->label[0]) {
b32 message = diagram_edge_is_message(d, (s32)i);
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"11\" text-anchor=\"%s\">",
ep.label_pos.x, ep.label_pos.y - (message ? 0.0f : 6.0f), c_dim, (message && e->src == e->dst) ? "start" : "middle");
svg_escape(&b, e->label);
String8 doc = diagram_doc(d, e->doc_off, e->doc_len);
if(doc.size) { strbuf_fmt(&b, "<title>"); svg_escape_n(&b, doc); strbuf_fmt(&b, "</title>"); }
strbuf_fmt(&b, "</text>\n");
}
}
// 3. Regular nodes (a link wraps the node in <a>, the doc becomes its hover <title>)
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->kind == NODE_MODULE || diagram_node_hidden(d, (s32)i)) continue;
char stroke[16];
svg_color(stroke, sizeof(stroke), n->color ? n->color : colors[3]);
char url[1024] = {};
if(n->link[0]) diagram_link_url(d, n->link, url, sizeof(url));
if(url[0]) { strbuf_fmt(&b, "<a href=\""); svg_escape(&b, url); strbuf_fmt(&b, "\" target=\"_blank\">\n"); }
strbuf_fmt(&b, "<g>");
String8 doc = diagram_doc(d, n->doc_off, n->doc_len);
if(doc.size || n->link[0]) {
strbuf_fmt(&b, "<title>");
svg_escape(&b, n->name);
if(n->link[0]) { strbuf_fmt(&b, " ("); svg_escape(&b, n->link); strbuf_fmt(&b, ")"); }
if(doc.size) { strbuf_fmt(&b, "\n\n"); svg_escape_n(&b, doc); }
strbuf_fmt(&b, "</title>\n");
}
if(node_kind_is_lifeline(n->kind)) {
f32 cx = n->x + n->w * 0.5f;
strbuf_fmt(&b, "<line x1=\"%.1f\" y1=\"%.1f\" x2=\"%.1f\" y2=\"%.1f\" stroke=\"%s\" stroke-dasharray=\"6 5\" stroke-width=\"1.2\"/>\n",
cx, n->y + n->header_h, cx, n->y + n->h, c_dim);
if(n->kind == NODE_ACTOR) {
f32 hy = n->y + 10.0f;
strbuf_fmt(&b, "<circle cx=\"%.1f\" cy=\"%.1f\" r=\"7\" fill=\"none\" stroke=\"%s\" stroke-width=\"1.5\"/>\n", cx, hy, stroke);
strbuf_fmt(&b, "<path d=\"M %.1f %.1f L %.1f %.1f M %.1f %.1f L %.1f %.1f M %.1f %.1f L %.1f %.1f L %.1f %.1f\" fill=\"none\" stroke=\"%s\" stroke-width=\"1.5\"/>\n",
cx, hy + 7.0f, cx, hy + 24.0f, cx - 11.0f, hy + 13.0f, cx + 11.0f, hy + 13.0f,
cx - 9.0f, hy + 36.0f, cx, hy + 24.0f, cx + 9.0f, hy + 36.0f, stroke);
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"12\" font-weight=\"600\" text-anchor=\"middle\">", cx, n->y + 58.0f, c_txt);
svg_escape(&b, n->name);
strbuf_fmt(&b, "</text>\n");
} else {
strbuf_fmt(&b, "<rect x=\"%.1f\" y=\"%.1f\" width=\"%.1f\" height=\"%.1f\" fill=\"%s\" stroke=\"%s\" stroke-width=\"1.2\"/>\n",
n->x, n->y, n->w, n->header_h, c_hdr, stroke);
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"12\" font-weight=\"600\" text-anchor=\"middle\">", cx, n->y + 20.0f, c_txt);
svg_escape(&b, n->name);
strbuf_fmt(&b, "</text>\n");
}
if(n->stereotype[0]) {
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"9.5\" text-anchor=\"middle\">", cx, n->y + n->header_h - 8.0f, c_dim);
svg_escape(&b, n->stereotype);
strbuf_fmt(&b, "</text>\n");
}
strbuf_fmt(&b, "</g>%s\n", url[0] ? "</a>" : "");
continue;
}
f32 rx = (n->kind == NODE_STATE) ? 14.0f : 0.0f;
strbuf_fmt(&b, "<rect x=\"%.1f\" y=\"%.1f\" width=\"%.1f\" height=\"%.1f\" rx=\"%.1f\" fill=\"%s\" stroke=\"%s\" stroke-width=\"1.2\"%s/>\n",
n->x, n->y, n->w, n->h, rx, c_panel, stroke, n->border_style == BORDER_DASHED ? " stroke-dasharray=\"5 3\"" : "");
strbuf_fmt(&b, "<rect x=\"%.1f\" y=\"%.1f\" width=\"%.1f\" height=\"%.1f\" rx=\"%.1f\" fill=\"%s\"/>\n",
n->x + 1, n->y + 1, n->w - 2, n->header_h - 1, rx, c_hdr);
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"12\" font-weight=\"600\">", n->x + 10.0f, n->y + 20.0f, c_txt);
svg_escape(&b, n->name);
strbuf_fmt(&b, "</text>\n");
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"9\" text-anchor=\"end\">%s</text>\n",
n->x + n->w - 8.0f, n->y + 19.0f, c_acc, node_kind_badge(n->kind));
if(!n->collapsed) {
f32 y = n->y + n->header_h;
if(n->note[0]) {
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"10\">", n->x + 10.0f, y + 16.0f, c_dim);
svg_escape(&b, n->note);
strbuf_fmt(&b, "</text>\n");
y += 24.0f;
}
for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) {
NodeSection *sec = &d->sections[s];
strbuf_fmt(&b, "<line x1=\"%.1f\" y1=\"%.1f\" x2=\"%.1f\" y2=\"%.1f\" stroke=\"%s\" stroke-opacity=\"0.35\"/>\n",
n->x, y, n->x + n->w, y, stroke);
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"9.5\">", n->x + 8.0f, y + 14.0f, c_dim);
svg_escape(&b, sec->title);
strbuf_fmt(&b, "</text>\n");
y += 20.0f;
if(!sec->collapsed) {
for(s32 m = sec->first_member; m >= 0; m = d->members[m].next) {
NodeMember *mem = &d->members[m];
strbuf_fmt(&b, "<text x=\"%.1f\" y=\"%.1f\" fill=\"%s\" font-size=\"11\">", n->x + 10.0f, y + 14.0f, c_txt);
if(mem->visibility) strbuf_fmt(&b, "%c ", mem->visibility);
svg_escape(&b, mem->name);
if(mem->type[0]) { strbuf_fmt(&b, " : "); svg_escape(&b, mem->type); }
strbuf_fmt(&b, "</text>\n");
y += 20.0f;
}
y += 4.0f;
}
}
}
strbuf_fmt(&b, "</g>%s\n", url[0] ? "</a>" : "");
}
strbuf_fmt(&b, "</svg>\n");
FILE *f = fopen(path, "wb");
if(!f) { scratch_end(&scratch); return false; }
fwrite(b.data, 1, b.size, f);
fclose(f);
scratch_end(&scratch);
return true;
}
//- C/C++ codebase structure scanner (:scan <file_or_dir>)
internal b32 is_ident_char(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
internal void scan_cpp_file(Diagram *d, Arena *arena, const char *path, s32 parent_module)
{
String8 text = FileLoad(arena, str8((char *)path));
if(text.size == 0) return;
const char *at = (const char *)text.data;
const char *end = at + text.size;
const char *line_at = at; // newlines counted up to here
u32 line = 1;
while(at < end) {
// skip comments
if(at + 1 < end && at[0] == '/' && at[1] == '/') { while(at < end && *at != '\n') ++at; continue; }
if(at + 1 < end && at[0] == '/' && at[1] == '*') { at += 2; while(at + 1 < end && !(at[0] == '*' && at[1] == '/')) ++at; at += 2; continue; }
// match struct/class/enum declaration
NodeKind kind = NODE_KIND_COUNT;
u32 kw_len = 0;
if(at + 7 < end && !strncmp(at, "struct ", 7) && (at == (const char *)text.data || !is_ident_char(at[-1]))) { kind = NODE_STRUCT; kw_len = 7; }
else if(at + 6 < end && !strncmp(at, "class ", 6) && (at == (const char *)text.data || !is_ident_char(at[-1]))) { kind = NODE_CLASS; kw_len = 6; }
else if(at + 5 < end && !strncmp(at, "enum ", 5) && (at == (const char *)text.data || !is_ident_char(at[-1]))) { kind = NODE_ENUM; kw_len = 5; }
if(kind == NODE_KIND_COUNT) { ++at; continue; }
for(; line_at < at; ++line_at) if(*line_at == '\n') ++line;
u32 decl_line = line;
at += kw_len;
while(at < end && (*at == ' ' || *at == '\t')) ++at;
if(kind == NODE_ENUM && at + 6 < end && !strncmp(at, "class ", 6)) { at += 6; while(at < end && *at == ' ') ++at; }
char name[64] = {};
u32 nlen = 0;
while(at < end && is_ident_char(*at) && nlen + 1 < sizeof(name)) name[nlen++] = *at++;
if(nlen == 0) continue;
// find '{' before ';'
const char *scan = at;
char base_name[64] = {};
while(scan < end && *scan != '{' && *scan != ';') {
if(*scan == ':' && !base_name[0]) {
++scan;
while(scan < end && (*scan == ' ' || *scan == '\t')) ++scan;
if(scan + 7 < end && !strncmp(scan, "public ", 7)) scan += 7;
else if(scan + 10 < end && !strncmp(scan, "protected ", 10)) scan += 10;
while(scan < end && (*scan == ' ' || *scan == '\t')) ++scan;
u32 bl = 0;
while(scan < end && is_ident_char(*scan) && bl + 1 < sizeof(base_name)) base_name[bl++] = *scan++;
continue;
}
++scan;
}
if(scan >= end || *scan != '{') continue;
at = scan + 1;
// create node (skip duplicates)
if(d->live_nodes >= DIAGRAM_MAX_NODES - 4) return;
s32 node = diagram_add_node(d, kind, name, 0, 0);
if(node < 0) continue;
if(parent_module >= 0) d->nodes[node].parent = parent_module;
if(base_name[0]) snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), ": %s", base_name);
const char *slash = strrchr(path, '/');
snprintf(d->nodes[node].tag, sizeof(d->nodes[node].tag), "%s", slash ? slash + 1 : path);
// NOTE: the absolute path for now, diagram_scan_cpp makes it relative to the repo
snprintf(d->nodes[node].link, sizeof(d->nodes[node].link), "%s:%u", path, decl_line);
s32 sec = diagram_add_section(d, node, kind == NODE_ENUM ? "values" : "fields");
u32 brace_depth = 1;
u32 member_cap = 0;
while(at < end && brace_depth > 0) {
if(at + 1 < end && at[0] == '/' && at[1] == '/') { while(at < end && *at != '\n') ++at; continue; }
if(at + 1 < end && at[0] == '/' && at[1] == '*') { at += 2; while(at + 1 < end && !(at[0] == '*' && at[1] == '/')) ++at; at += 2; continue; }
if(*at == '{') { ++brace_depth; ++at; continue; }
if(*at == '}') { --brace_depth; ++at; continue; }
if(brace_depth == 1 && (*at != ' ' && *at != '\t' && *at != '\n' && *at != '\r' && *at != '#')) {
const char *ls = at;
while(at < end && *at != ';' && *at != '\n' && *at != ',' && *at != '{' && *at != '}') ++at;
if(member_cap < 14) {
char stmt[160] = {};
u64 sl = Min((u64)(at - ls), (u64)sizeof(stmt) - 1);
MemCpy(stmt, ls, sl);
// trim comments / trailing ws
char *cmm = strstr(stmt, "//");
if(cmm) *cmm = 0;
u32 len2 = (u32)strlen(stmt);
while(len2 > 0 && (stmt[len2 - 1] == ' ' || stmt[len2 - 1] == '\t' || stmt[len2 - 1] == '\r')) stmt[--len2] = 0;
if(len2 > 0 && strcmp(stmt, "public:") != 0 && strcmp(stmt, "private:") != 0 && strcmp(stmt, "protected:") != 0) {
if(kind == NODE_ENUM) {
char *eq = strchr(stmt, '=');
if(eq) *eq = 0;
diagram_add_member(d, sec, 0, stmt, "", "");
++member_cap;
} else {
// split last identifier as field name, rest as type
char *last_sp = strrchr(stmt, ' ');
if(last_sp && last_sp[1]) {
*last_sp = 0;
const char *fname = last_sp + 1;
b32 is_ptr = false;
while(*fname == '*') { is_ptr = true; ++fname; }
char ftype[80];
snprintf(ftype, sizeof(ftype), "%s%s", stmt, is_ptr ? "*" : "");
diagram_add_member(d, sec, '+', fname, ftype, "");
++member_cap;
}
}
}
}
}
if(at < end && *at != '{' && *at != '}') ++at;
}
}
}
internal b32 app_path_is_dir(const char *path)
{
#if PLATFORM_WINDOWS
WCHAR wide[MAX_PATH * 2];
win32_utf8_to_wide(path, -1, wide, ArrayCount(wide));
DWORD attributes = GetFileAttributesW(wide);
return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY);
#else
struct stat st;
return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
#endif
}
internal b32 scan_is_header(const char *name)
{
u64 len = strlen(name);
return (len > 2 && !strcmp(name + len - 2, ".h")) || (len > 4 && !strcmp(name + len - 4, ".hpp"));
}
internal b32 scan_skip_dir(const char *name)
{
return name[0] == '.' || !strcmp(name, "build") || !strcmp(name, "protocols") || !strcmp(name, "node_modules");
}
#if PLATFORM_WINDOWS
internal void scan_cpp_dir(Diagram *d, Arena *arena, const char *path, u32 depth)
{
if(depth > 4) return;
WCHAR wide[MAX_PATH * 2];
win32_utf8_to_wide(path, -1, wide, ArrayCount(wide));
DWORD attributes = GetFileAttributesW(wide);
if(attributes == INVALID_FILE_ATTRIBUTES) return;
if(!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
if(scan_is_header(path)) scan_cpp_file(d, arena, path, -1);
return;
}
const char *base = strrchr(path, '/');
const char *back = strrchr(path, '\\');
if(back && (!base || back > base)) base = back;
s32 mod = -1;
if(depth > 0 && base && base[1]) {
mod = diagram_add_node(d, NODE_MODULE, base + 1, 0, 0);
}
WCHAR pattern[MAX_PATH * 2];
int length = win32_utf8_to_wide(path, -1, pattern, ArrayCount(pattern) - 3);
pattern[length++] = L'\\';
pattern[length++] = L'*';
pattern[length] = 0;
WIN32_FIND_DATAW data;
HANDLE find = FindFirstFileW(pattern, &data);
if(find == INVALID_HANDLE_VALUE) return;
do {
char name[MAX_PATH * 4];
win32_wide_to_utf8(data.cFileName, -1, name, sizeof(name));
if(scan_skip_dir(name)) continue;
char child[640];
snprintf(child, sizeof(child), "%s/%s", path, name);
if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if(!(data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) scan_cpp_dir(d, arena, child, depth + 1);
} else if(scan_is_header(name)) {
scan_cpp_file(d, arena, child, mod);
}
} while(FindNextFileW(find, &data));
FindClose(find);
}
#else
internal void scan_cpp_dir(Diagram *d, Arena *arena, const char *path, u32 depth)
{
if(depth > 4) return;
struct stat st;
if(stat(path, &st) != 0) return;
if(S_ISREG(st.st_mode)) {
if(scan_is_header(path)) scan_cpp_file(d, arena, path, -1);
return;
}
if(!S_ISDIR(st.st_mode)) return;
DIR *dir = opendir(path);
if(!dir) return;
const char *base = strrchr(path, '/');
s32 mod = -1;
if(depth > 0 && base && base[1]) {
mod = diagram_add_node(d, NODE_MODULE, base + 1, 0, 0);
}
struct dirent *ent;
while((ent = readdir(dir)) != NULL) {
if(scan_skip_dir(ent->d_name)) continue;
char child[640];
snprintf(child, sizeof(child), "%s/%s", path, ent->d_name);
struct stat cst;
if(stat(child, &cst) != 0) continue;
if(S_ISDIR(cst.st_mode)) {
scan_cpp_dir(d, arena, child, depth + 1);
} else if(scan_is_header(ent->d_name)) {
scan_cpp_file(d, arena, child, mod);
}
}
closedir(dir);
}
#endif
internal u32 diagram_scan_cpp(Diagram *d, const char *path)
{
ScratchArena scratch = ScratchGet();
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "Codebase: %s", path);
char abs[1024];
path_make_absolute(path, abs, sizeof(abs));
scan_cpp_dir(d, scratch.arena, abs, 0);
// NOTE: links relative to the git checkout around the scanned folder (or the folder itself),
// with the origin remote as the repo url so gx opens the right line online
char root[1024], dir[1024];
if(app_path_is_dir(abs)) snprintf(dir, sizeof(dir), "%s", abs);
else path_dirname(abs, dir, sizeof(dir));
if(!diagram_detect_repo(d, dir, root, sizeof(root))) snprintf(root, sizeof(root), "%s", dir);
snprintf(d->repo_root, sizeof(d->repo_root), "%s", root);
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || !n->link[0]) continue;
char rel[DIAGRAM_LINK_SIZE];
path_relative_to(n->link, root, rel, sizeof(rel));
snprintf(n->link, sizeof(n->link), "%s", rel);
}
// infer relationships from member types and inheritance stereotypes!
for(u32 i = 0; i < d->node_count; ++i) {
DiagramNode *n = &d->nodes[i];
if(!n->alive || n->kind == NODE_MODULE) continue;
// inheritance from ": Base"
if(n->stereotype[0] == ':' && n->stereotype[1] == ' ') {
const char *base = n->stereotype + 2;
for(u32 j = 0; j < d->node_count; ++j) {
if(i != j && d->nodes[j].alive && !strcmp(d->nodes[j].name, base)) {
diagram_add_edge(d, (s32)i, (s32)j, EDGE_INHERITANCE, "extends");
break;
}
}
}
// composition / association from member types
for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) {
for(s32 m = d->sections[s].first_member; m >= 0; m = d->members[m].next) {
NodeMember *mem = &d->members[m];
if(!mem->type[0]) continue;
b32 is_ptr = (strchr(mem->type, '*') != NULL);
for(u32 j = 0; j < d->node_count; ++j) {
if(i == j || !d->nodes[j].alive || d->nodes[j].kind == NODE_MODULE) continue;
if(strlen(d->nodes[j].name) < 3) continue;
const char *hit = strstr(mem->type, d->nodes[j].name);
if(hit) {
b32 left_ok = (hit == mem->type || !is_ident_char(hit[-1]));
u64 tlen = strlen(d->nodes[j].name);
b32 right_ok = !is_ident_char(hit[tlen]);
if(left_ok && right_ok) {
// avoid duplicate edge between same pair
b32 exists = false;
for(u32 e = 0; e < d->edge_count; ++e) {
if(d->edges[e].alive && d->edges[e].src == (s32)i && d->edges[e].dst == (s32)j) { exists = true; break; }
}
if(!exists) {
s32 ei = diagram_add_edge(d, (s32)i, (s32)j, is_ptr ? EDGE_ASSOCIATION : EDGE_COMPOSITION, mem->name);
if(ei >= 0) d->edges[ei].src_member = m;
}
break;
}
}
}
}
}
}
// prune empty module containers
for(u32 i = 0; i < d->node_count; ++i) {
if(d->nodes[i].alive && d->nodes[i].kind == NODE_MODULE) {
b32 any = false;
for(u32 j = 0; j < d->node_count; ++j) if(d->nodes[j].alive && d->nodes[j].parent == (s32)i) { any = true; break; }
if(!any) diagram_delete_node(d, (s32)i);
}
}
diagram_layout_layered(d, false);
diagram_rebuild_tags(d);
scratch_end(&scratch);
return d->live_nodes;
}
//- built-in showcase templates
global_variable const DiagramTemplate diagram_templates[] = {
{"arch", "Design-It Vulkan + Wayland Engine Architecture (default)"},
{"ecs", "Data-Oriented ECS Game Engine"},
{"microservices", "Event-Driven Distributed Backend"},
{"compiler", "Optimizing Compiler Frontend -> SSA IR -> Codegen"},
{"uml", "Classic UML Domain & Design Patterns"},
{"sequence", "Sequence Diagram: login with a token cache"},
{"stress", "1,000 Nodes / 2,000 Edges Performance Benchmark"},
};
internal u32 diagram_template_count(void) { return ArrayCount(diagram_templates); }
internal const DiagramTemplate *diagram_template_info(u32 index) { return index < ArrayCount(diagram_templates) ? &diagram_templates[index] : &diagram_templates[0]; }
internal void template_load_arch(Diagram *d)
{
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "Design-It Software Architecture");
d->default_routing = ROUTE_ORTHOGONAL;
// Containers
s32 m_plat = diagram_add_node(d, NODE_MODULE, "Platform & Host", 0, 0);
snprintf(d->nodes[m_plat].tag, sizeof(d->nodes[m_plat].tag), "platform");
s32 m_ren = diagram_add_node(d, NODE_MODULE, "Vulkan 1.3 SDF Renderer", 0, 0);
snprintf(d->nodes[m_ren].tag, sizeof(d->nodes[m_ren].tag), "render");
s32 m_diag = diagram_add_node(d, NODE_MODULE, "Diagram Graph Engine", 0, 0);
snprintf(d->nodes[m_diag].tag, sizeof(d->nodes[m_diag].tag), "diagram");
s32 m_ui = diagram_add_node(d, NODE_MODULE, "RAD-Style Dockable UI (.so)", 0, 0);
snprintf(d->nodes[m_ui].tag, sizeof(d->nodes[m_ui].tag), "ui");
// Platform nodes
s32 n_app = diagram_add_node(d, NODE_SYSTEM, "AppHost", 60, 80);
d->nodes[n_app].parent = m_plat;
snprintf(d->nodes[n_app].stereotype, sizeof(d->nodes[n_app].stereotype), "event-driven main loop");
snprintf(d->nodes[n_app].tag, sizeof(d->nodes[n_app].tag), "platform");
s32 s = diagram_add_section(d, n_app, "state");
s32 m_app_win = diagram_add_member(d, s, '+', "window", "PlatformWindow*", "wayland");
s32 m_app_ren = diagram_add_member(d, s, '+', "renderer", "VulkanRenderer", "vk1.3");
s32 m_app_dia = diagram_add_member(d, s, '+', "diagram", "Diagram*", "hot-safe");
diagram_add_member(d, s, '+', "ui_code", "UiCode (.so)", "inotify");
s = diagram_add_section(d, n_app, "loop");
diagram_add_member(d, s, '+', "poll_idle()", "0% cpu idle", "O(1)");
diagram_add_member(d, s, '+', "hot_reload()", "dlopen .so", "live");
s32 n_wl = diagram_add_node(d, NODE_INTERFACE, "PlatformWindow", 60, 380);
d->nodes[n_wl].parent = m_plat;
snprintf(d->nodes[n_wl].stereotype, sizeof(d->nodes[n_wl].stereotype), "xdg-shell + layer-shell");
snprintf(d->nodes[n_wl].tag, sizeof(d->nodes[n_wl].tag), "platform");
s = diagram_add_section(d, n_wl, "events");
diagram_add_member(d, s, '@', "keyboard", "xkbcommon utf8", "");
diagram_add_member(d, s, '@', "pointer", "pos + scroll_x/y", "");
diagram_add_member(d, s, '@', "frame_cb", "compositor paced", "vsync");
// Render nodes
s32 n_vk = diagram_add_node(d, NODE_SYSTEM, "VulkanRenderer", 460, 80);
d->nodes[n_vk].parent = m_ren;
snprintf(d->nodes[n_vk].stereotype, sizeof(d->nodes[n_vk].stereotype), "dynamic rendering + sync2");
snprintf(d->nodes[n_vk].tag, sizeof(d->nodes[n_vk].tag), "render");
s = diagram_add_section(d, n_vk, "pipeline");
diagram_add_member(d, s, '+', "frames[2]", "VulkanFrame", "in-flight");
diagram_add_member(d, s, '+', "pipeline", "1 instanced SDF", "hot");
s32 m_vk_atlas = diagram_add_member(d, s, '+', "atlas", "R8 2048x2048", "4 MB");
s = diagram_add_section(d, n_vk, "methods");
diagram_add_member(d, s, '+', "vk_frame_begin()", "DrawInstance*", "mapped");
diagram_add_member(d, s, '+', "vk_render()", "1 draw / clip", "<0.4ms");
s32 n_inst = diagram_add_node(d, NODE_STRUCT, "DrawInstance", 460, 380);
d->nodes[n_inst].parent = m_ren;
snprintf(d->nodes[n_inst].stereotype, sizeof(d->nodes[n_inst].stereotype), "32 bytes (2 per cacheline)");
snprintf(d->nodes[n_inst].tag, sizeof(d->nodes[n_inst].tag), "hot");
s = diagram_add_section(d, n_inst, "memory layout");
diagram_add_member(d, s, '+', "rect[4]", "f32 (x0,y0,x1,y1)", "0x00");
diagram_add_member(d, s, '+', "data[2]", "u32 packed SDF/UV", "0x10");
diagram_add_member(d, s, '+', "colors[2]", "u32 top/bottom", "0x18");
s = diagram_add_section(d, n_inst, "SDF kinds");
diagram_add_member(d, s, '*', "RECT / CIRCLE / DIAMOND", "exact SDF", "");
diagram_add_member(d, s, '*', "LINE / ARROW / GLYPH", "dashed+orient", "gpu");
s32 n_font = diagram_add_node(d, NODE_STORAGE, "FontSystem", 840, 80);
d->nodes[n_font].parent = m_ren;
snprintf(d->nodes[n_font].stereotype, sizeof(d->nodes[n_font].stereotype), "FreeType + HarfBuzz");
snprintf(d->nodes[n_font].tag, sizeof(d->nodes[n_font].tag), "render");
s = diagram_add_section(d, n_font, "caches");
diagram_add_member(d, s, '+', "glyphs[16384]", "open-addr table", "O(1)");
diagram_add_member(d, s, '+', "runs[8192]", "shaped runs", "cached");
diagram_add_member(d, s, '+', "recent[1024]", "ptr fastpath", "ns");
// Diagram engine nodes
s32 n_diag = diagram_add_node(d, NODE_STRUCT, "Diagram", 460, 710);
d->nodes[n_diag].parent = m_diag;
snprintf(d->nodes[n_diag].stereotype, sizeof(d->nodes[n_diag].stereotype), "flat arena pools");
snprintf(d->nodes[n_diag].tag, sizeof(d->nodes[n_diag].tag), "diagram");
s = diagram_add_section(d, n_diag, "pools");
diagram_add_member(d, s, '+', "nodes[4096]", "DiagramNode*", "index-id");
diagram_add_member(d, s, '+', "edges[8192]", "DiagramEdge*", "routed");
diagram_add_member(d, s, '+', "sections[8192]", "NodeSection*", "custom");
diagram_add_member(d, s, '+', "members[32768]", "NodeMember*", "pin-able");
s = diagram_add_section(d, n_diag, "history");
diagram_add_member(d, s, '+', "undo_ring[32]", "Arena snapshots", "O(N)");
s32 n_lay = diagram_add_node(d, NODE_SYSTEM, "AutoLayout & Router", 840, 710);
d->nodes[n_lay].parent = m_diag;
snprintf(d->nodes[n_lay].stereotype, sizeof(d->nodes[n_lay].stereotype), "zero-heap scratch arena");
snprintf(d->nodes[n_lay].tag, sizeof(d->nodes[n_lay].tag), "diagram");
s = diagram_add_section(d, n_lay, "algorithms");
diagram_add_member(d, s, '+', "layout_layered()", "Sugiyama ranks", "DAG");
diagram_add_member(d, s, '+', "layout_force()", "Fruchterman-R", "spring");
diagram_add_member(d, s, '+', "edge_route()", "ortho / bezier", "ports");
s32 n_io = diagram_add_node(d, NODE_SYSTEM, "Codec & C++ Scanner", 840, 930);
d->nodes[n_io].parent = m_diag;
snprintf(d->nodes[n_io].stereotype, sizeof(d->nodes[n_io].stereotype), ".dit / .dit.txt / .svg");
snprintf(d->nodes[n_io].tag, sizeof(d->nodes[n_io].tag), "diagram");
s = diagram_add_section(d, n_io, "pipelines");
diagram_add_member(d, s, '+', "dsl_parse/emit()", "git-friendly", "2-way");
diagram_add_member(d, s, '+', "export_svg()", "themed vector", "exact");
diagram_add_member(d, s, '+', "scan_cpp()", "header -> UML", "auto");
// UI nodes
s32 n_ui = diagram_add_node(d, NODE_CLASS, "DockableLayout", 60, 710);
d->nodes[n_ui].parent = m_ui;
snprintf(d->nodes[n_ui].stereotype, sizeof(d->nodes[n_ui].stereotype), "binary split tree");
snprintf(d->nodes[n_ui].tag, sizeof(d->nodes[n_ui].tag), "ui");
s = diagram_add_section(d, n_ui, "views");
diagram_add_member(d, s, '+', "Canvas", "infinite pan/zoom", "LOD");
diagram_add_member(d, s, '+', "Outline / Edges", "watch tables", "vim");
diagram_add_member(d, s, '+', "Inspector / Source", "inline + DSL", "live");
diagram_add_member(d, s, '+', "Settings / Profiler", "18 colors+heap", "2Hz");
// Note
s32 n_note = diagram_add_node(d, NODE_NOTE, "Quick Reference", 840, 380);
snprintf(d->nodes[n_note].tag, sizeof(d->nodes[n_note].tag), "ui");
snprintf(d->nodes[n_note].note, sizeof(d->nodes[n_note].note), "Drag nodes, scroll to zoom, : for commands");
s = diagram_add_section(d, n_note, "keys");
diagram_add_member(d, s, '*', "a / e / dd / u", "add / edge / del / undo", "");
diagram_add_member(d, s, '*', "f / 0 / G / F", "fit / 100% / grid / focus", "");
diagram_add_member(d, s, '*', ":scan / :tpl / :export", "C++ / templates / svg", "");
diagram_add_member(d, s, '*', "^w v / ^w s / :view", "split / open views", "");
// Edges (showcasing member pinning, UML kinds, multiplicities, animated dataflow)
s32 e;
e = diagram_add_edge(d, n_app, n_wl, EDGE_COMPOSITION, "owns surface");
d->edges[e].src_member = m_app_win;
snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "1");
snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "1");
e = diagram_add_edge(d, n_app, n_vk, EDGE_COMPOSITION, "presents");
d->edges[e].src_member = m_app_ren;
e = diagram_add_edge(d, n_app, n_diag, EDGE_ASSOCIATION, "persists");
d->edges[e].src_member = m_app_dia;
e = diagram_add_edge(d, n_vk, n_inst, EDGE_DATAFLOW, "131k mapped GPU");
snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "0..131k");
snprintf(d->edges[e].tag, sizeof(d->edges[e].tag), "hot");
e = diagram_add_edge(d, n_vk, n_font, EDGE_DEPENDENCY, "uploads dirty rows");
d->edges[e].src_member = m_vk_atlas;
e = diagram_add_edge(d, n_ui, n_diag, EDGE_BIDIR, "reads & mutates");
e = diagram_add_edge(d, n_ui, n_inst, EDGE_DATAFLOW, "emits quads");
snprintf(d->edges[e].tag, sizeof(d->edges[e].tag), "hot");
e = diagram_add_edge(d, n_diag, n_lay, EDGE_DEPENDENCY, "ranks & routes");
e = diagram_add_edge(d, n_io, n_diag, EDGE_ASSOCIATION, "parse / serialize");
diagram_measure_all(d);
diagram_fit_containers(d);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void template_load_ecs(Diagram *d)
{
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "Data-Oriented ECS Game Engine");
d->default_routing = ROUTE_ORTHOGONAL;
s32 m_mem = diagram_add_node(d, NODE_MODULE, "Archetype Storage", 0, 0);
s32 m_sys = diagram_add_node(d, NODE_MODULE, "Parallel Scheduler", 0, 0);
s32 world = diagram_add_node(d, NODE_STRUCT, "World", 0, 0);
s32 s = diagram_add_section(d, world, "tables");
diagram_add_member(d, s, '+', "entities", "SparseSet<EntitySlot>", "O(1)");
diagram_add_member(d, s, '+', "archetypes", "HashMap<Sig, Arch*>", "");
s32 arch = diagram_add_node(d, NODE_STRUCT, "Archetype", 0, 0);
d->nodes[arch].parent = m_mem;
s = diagram_add_section(d, arch, "layout");
diagram_add_member(d, s, '+', "signature", "u64[4] bitset", "256c");
diagram_add_member(d, s, '+', "chunks", "Chunk* list", "SoA");
s32 chunk = diagram_add_node(d, NODE_STORAGE, "Chunk (16 KB)", 0, 0);
d->nodes[chunk].parent = m_mem;
snprintf(d->nodes[chunk].stereotype, sizeof(d->nodes[chunk].stereotype), "L1 cache aligned");
s = diagram_add_section(d, chunk, "columns");
diagram_add_member(d, s, '+', "pos_x / pos_y", "f32[N]", "SIMD");
diagram_add_member(d, s, '+', "vel_x / vel_y", "f32[N]", "AVX2");
s32 sched = diagram_add_node(d, NODE_SYSTEM, "JobScheduler", 0, 0);
d->nodes[sched].parent = m_sys;
s = diagram_add_section(d, sched, "workers");
diagram_add_member(d, s, '+', "queues[N]", "WorkStealingDeque", "lock-free");
diagram_add_member(d, s, '+', "dispatch()", "DAG barrier", "");
s32 isys = diagram_add_node(d, NODE_INTERFACE, "ISystem", 0, 0);
d->nodes[isys].parent = m_sys;
s = diagram_add_section(d, isys, "contract");
diagram_add_member(d, s, '+', "query()", "ReadMask / WriteMask", "pure");
diagram_add_member(d, s, '+', "tick(Chunk*)", "void", "hot");
s32 phys = diagram_add_node(d, NODE_CLASS, "PhysicsSystem", 0, 0);
d->nodes[phys].parent = m_sys;
s32 rend = diagram_add_node(d, NODE_CLASS, "RenderExtract", 0, 0);
d->nodes[rend].parent = m_sys;
diagram_add_edge(d, world, arch, EDGE_COMPOSITION, "owns");
diagram_add_edge(d, arch, chunk, EDGE_COMPOSITION, "16KB slabs");
diagram_add_edge(d, sched, isys, EDGE_AGGREGATION, "schedules");
diagram_add_edge(d, phys, isys, EDGE_IMPLEMENTS, "implements");
diagram_add_edge(d, rend, isys, EDGE_IMPLEMENTS, "implements");
diagram_add_edge(d, phys, chunk, EDGE_DATAFLOW, "SIMD write");
diagram_add_edge(d, rend, chunk, EDGE_DATAFLOW, "RO gather");
diagram_layout_layered(d, false);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void template_load_microservices(Diagram *d)
{
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "Event-Driven Distributed Architecture");
d->default_routing = ROUTE_BEZIER;
s32 gw = diagram_add_node(d, NODE_SYSTEM, "Edge Gateway", 0, 0);
snprintf(d->nodes[gw].tag, sizeof(d->nodes[gw].tag), "edge");
s32 s = diagram_add_section(d, gw, "routes");
diagram_add_member(d, s, '@', "/v1/orders", "gRPC proxy", "TLS");
diagram_add_member(d, s, '@', "/v1/auth", "JWT verify", "5ms");
s32 auth = diagram_add_node(d, NODE_SYSTEM, "Auth Service", 0, 0);
snprintf(d->nodes[auth].tag, sizeof(d->nodes[auth].tag), "core");
s32 ord = diagram_add_node(d, NODE_SYSTEM, "Order Service", 0, 0);
snprintf(d->nodes[ord].tag, sizeof(d->nodes[ord].tag), "core");
s32 inv = diagram_add_node(d, NODE_SYSTEM, "Inventory Worker", 0, 0);
snprintf(d->nodes[inv].tag, sizeof(d->nodes[inv].tag), "async");
s32 bill = diagram_add_node(d, NODE_SYSTEM, "Billing Worker", 0, 0);
snprintf(d->nodes[bill].tag, sizeof(d->nodes[bill].tag), "async");
s32 bus = diagram_add_node(d, NODE_STORAGE, "Event Bus (Kafka)", 0, 0);
snprintf(d->nodes[bus].tag, sizeof(d->nodes[bus].tag), "infra");
s = diagram_add_section(d, bus, "topics");
diagram_add_member(d, s, '@', "orders.created", "partition=16", "log");
diagram_add_member(d, s, '@', "payments.settled", "partition=8", "log");
s32 pg = diagram_add_node(d, NODE_STORAGE, "PostgreSQL Primary", 0, 0);
snprintf(d->nodes[pg].tag, sizeof(d->nodes[pg].tag), "infra");
s32 rds = diagram_add_node(d, NODE_STORAGE, "Redis Cluster", 0, 0);
snprintf(d->nodes[rds].tag, sizeof(d->nodes[rds].tag), "infra");
diagram_add_edge(d, gw, auth, EDGE_ASSOCIATION, "verify token");
diagram_add_edge(d, gw, ord, EDGE_DATAFLOW, "CreateOrder");
diagram_add_edge(d, auth, rds, EDGE_DEPENDENCY, "session cache");
diagram_add_edge(d, ord, pg, EDGE_DATAFLOW, "ACID write");
diagram_add_edge(d, ord, bus, EDGE_ASYNC, "publish event");
diagram_add_edge(d, bus, inv, EDGE_ASYNC, "reserve stock");
diagram_add_edge(d, bus, bill, EDGE_ASYNC, "charge card");
diagram_add_edge(d, inv, pg, EDGE_DEPENDENCY, "update qty");
diagram_layout_layered(d, true);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void template_load_compiler(Diagram *d)
{
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "Compiler Pipeline (Frontend -> SSA -> x64)");
d->default_routing = ROUTE_ORTHOGONAL;
s32 src = diagram_add_node(d, NODE_STORAGE, "Source Buffer", 0, 0);
s32 lex = diagram_add_node(d, NODE_SYSTEM, "Lexer", 0, 0);
s32 parse = diagram_add_node(d, NODE_SYSTEM, "Recursive Parser", 0, 0);
s32 ast = diagram_add_node(d, NODE_ENUM, "AST Node", 0, 0);
s32 s = diagram_add_section(d, ast, "variants");
diagram_add_member(d, s, '+', "Expr / Stmt", "tagged union", "arena");
diagram_add_member(d, s, '+', "Decl / Type", "index-linked", "flat");
s32 sema = diagram_add_node(d, NODE_SYSTEM, "Type Checker", 0, 0);
s32 ssa = diagram_add_node(d, NODE_STRUCT, "SSA IR Module", 0, 0);
s = diagram_add_section(d, ssa, "blocks");
diagram_add_member(d, s, '+', "BasicBlock[]", "dominator tree", "");
diagram_add_member(d, s, '+', "Inst[]", "3-address SSA", "phi");
s32 opt = diagram_add_node(d, NODE_STATE, "Opt Passes (GVN/DCE/Inline)", 0, 0);
s32 reg = diagram_add_node(d, NODE_SYSTEM, "Linear Scan RegAlloc", 0, 0);
s32 emit = diagram_add_node(d, NODE_SYSTEM, "x64 / ARM64 Emitter", 0, 0);
diagram_add_edge(d, src, lex, EDGE_DATAFLOW, "UTF-8 bytes");
diagram_add_edge(d, lex, parse, EDGE_DATAFLOW, "Token[]");
diagram_add_edge(d, parse, ast, EDGE_COMPOSITION, "builds");
diagram_add_edge(d, ast, sema, EDGE_DATAFLOW, "resolve");
diagram_add_edge(d, sema, ssa, EDGE_DATAFLOW, "lower");
diagram_add_edge(d, ssa, opt, EDGE_BIDIR, "fixed-point");
diagram_add_edge(d, ssa, reg, EDGE_DATAFLOW, "live intervals");
diagram_add_edge(d, reg, emit, EDGE_DATAFLOW, "machine ops");
diagram_layout_layered(d, true);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void template_load_uml(Diagram *d)
{
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "UML Class & Design Patterns");
d->default_routing = ROUTE_ORTHOGONAL;
s32 isub = diagram_add_node(d, NODE_INTERFACE, "Observer", 0, 0);
snprintf(d->nodes[isub].stereotype, sizeof(d->nodes[isub].stereotype), "<<interface>>");
s32 s = diagram_add_section(d, isub, "methods");
diagram_add_member(d, s, '+', "on_event(Event&)", "void", "abstract");
s32 node = diagram_add_node(d, NODE_CLASS, "SceneNode", 0, 0);
s = diagram_add_section(d, node, "attributes");
diagram_add_member(d, s, '-', "id", "u64", "");
diagram_add_member(d, s, '#', "transform", "Mat4", "");
s = diagram_add_section(d, node, "operations");
diagram_add_member(d, s, '+', "update(dt)", "void", "virtual");
s32 group = diagram_add_node(d, NODE_CLASS, "GroupNode", 0, 0);
s = diagram_add_section(d, group, "operations");
diagram_add_member(d, s, '+', "add_child(SceneNode*)", "void", "");
s32 mesh = diagram_add_node(d, NODE_CLASS, "MeshNode", 0, 0);
s32 bus = diagram_add_node(d, NODE_CLASS, "EventDispatcher", 0, 0);
s32 strat = diagram_add_node(d, NODE_INTERFACE, "CullStrategy", 0, 0);
snprintf(d->nodes[strat].stereotype, sizeof(d->nodes[strat].stereotype), "<<strategy>>");
s32 bvh = diagram_add_node(d, NODE_CLASS, "BVHCuller", 0, 0);
s32 e;
e = diagram_add_edge(d, group, node, EDGE_INHERITANCE, "extends");
e = diagram_add_edge(d, mesh, node, EDGE_INHERITANCE, "extends");
e = diagram_add_edge(d, group, node, EDGE_COMPOSITION, "children");
snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "1");
snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "0..*");
e = diagram_add_edge(d, bus, isub, EDGE_AGGREGATION, "listeners");
snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "1");
snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "0..*");
e = diagram_add_edge(d, node, isub, EDGE_IMPLEMENTS, "realizes");
e = diagram_add_edge(d, bvh, strat, EDGE_IMPLEMENTS, "realizes");
e = diagram_add_edge(d, group, strat, EDGE_DEPENDENCY, "uses");
diagram_layout_layered(d, false);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void template_load_stress(Diagram *d)
{
diagram_clear(d);
snprintf(d->title, sizeof(d->title), "Performance Benchmark (1,000 Nodes / 1,900 Edges)");
d->default_routing = ROUTE_STRAIGHT;
u32 cols = 40, rows = 25;
s32 ids[1000];
for(u32 r = 0; r < rows; ++r) {
for(u32 c = 0; c < cols; ++c) {
u32 idx = r * cols + c;
char name[32];
snprintf(name, sizeof(name), "Node_%03u", idx);
NodeKind k = (NodeKind)(idx % 8);
if(k == NODE_MODULE) k = NODE_STRUCT;
s32 n = diagram_add_node(d, k, name, (f32)c * 260.0f, (f32)r * 130.0f);
ids[idx] = n;
snprintf(d->nodes[n].tag, sizeof(d->nodes[n].tag), "layer_%u", r / 5);
s32 sec = diagram_add_section(d, n, "fields");
diagram_add_member(d, sec, '+', "value", "u64", "");
diagram_add_member(d, sec, '+', "next", "Node*", "");
}
}
for(u32 r = 0; r < rows; ++r) {
for(u32 c = 0; c < cols; ++c) {
u32 idx = r * cols + c;
if(c + 1 < cols) diagram_add_edge(d, ids[idx], ids[idx + 1], (idx % 5 == 0) ? EDGE_DATAFLOW : EDGE_ASSOCIATION, "");
if(r + 1 < rows) diagram_add_edge(d, ids[idx], ids[idx + cols], (idx % 3 == 0) ? EDGE_DEPENDENCY : EDGE_COMPOSITION, "");
}
}
diagram_measure_all(d);
diagram_rebuild_tags(d);
d->dirty = false;
}
internal void template_load_sequence(Diagram *d)
{
const char *text =
"diagram \"Login Sequence\" routing=orthogonal\n"
"doc \"\"\"\n"
" How a login request travels. Drag along a lifeline to add a message,\n"
" drag a message up or down to reorder it, :seq re-spaces everything.\n"
"\"\"\"\n"
"actor \"User\" id=user\n"
"lifeline \"Web App\" id=web stereo=\"frontend\"\n"
"lifeline \"Auth Service\" id=auth\n"
"lifeline \"Token Cache\" id=cache stereo=\"redis\"\n"
"lifeline \"User DB\" id=db stereo=\"postgres\"\n"
"user ->> web : \"submit credentials\"\n"
"web ->> auth : \"POST /login\" {\n"
" doc \"\"\"\n"
" Rate limited per IP: 10 attempts per minute.\n"
" \"\"\"\n"
"}\n"
"auth ->> cache : \"GET session:<user>\"\n"
"cache -->> auth : \"miss\"\n"
"auth ->> db : \"SELECT hash WHERE email\"\n"
"db -->> auth : \"row\"\n"
"auth ->> auth : \"verify argon2\"\n"
"auth ~> cache : \"SET session (ttl 1h)\"\n"
"auth -->> web : \"200 + token\"\n"
"web -->> user : \"dashboard\"\n";
diagram_from_dsl(d, str8((char *)text));
}
internal b32 diagram_load_template(Diagram *d, const char *name)
{
if(!strcasecmp(name, "arch")) { template_load_arch(d); return true; }
if(!strcasecmp(name, "ecs")) { template_load_ecs(d); return true; }
if(!strcasecmp(name, "microservices")) { template_load_microservices(d); return true; }
if(!strcasecmp(name, "compiler")) { template_load_compiler(d); return true; }
if(!strcasecmp(name, "uml")) { template_load_uml(d); return true; }
if(!strcasecmp(name, "sequence") || !strcasecmp(name, "seq")) { template_load_sequence(d); return true; }
if(!strcasecmp(name, "stress")) { template_load_stress(d); return true; }
return false;
}
|